Objects are mutable
Related code
class Dog: """Represents a dog.""" dog = Dog() dog.name = "Murki" dog.age = 2
You can change the state of an object by making an assignment to one of its attributes. For example, to change the name and age of a dog, you can modify the values of name and age:
... >>> dog.name Murki >>> dog.age 2 >>> dog.name = "Rreshki" >>> dog.age = 3 >>> dog.name, dog.age ('Rreshki', 3)
You can also update the value of the attribute based on its current value:
... >>> dog.age 3 >>> dog.age = dog.age + 2 >>> dog.age 5
pass
A class definition with no statement in its body gives error:
class Dog:
IndentationError('expected an indented block after class definition on line 1', ('<string>', 1, 11, 'class Dog:\n', 1, -1)) >>>
We can write a docstring, or we can use pass
keyword,
which is used as a placeholder for the code to come. In our case we can use it to avoid error:
class Dog: pass
Exercises
class Room: pass r = Room() r.name = "Living Room" r.lights_on = False r.lights_on = True
What is the value of the following expressions at the end of execution of the above script?
r.name: | |
r.lights_on: |
Exercises
Create a class, Car
Create a dog, my_car, with two attributes, brand and year.
Change my_car's brand
Add one year to my_car
Create a class, Cup
Create a cup, c, with two attributes, color and volume.
Change c's color
Add 50 to c's volume
Create a class, Fruit
Create a fruit, f, with one attribute, type.
Change f's type
Create a class, Shoe
Create a shoe, s, with one attribute, size.
Add 1 to s's size
class Horse: pass h = Horse() h.name = "Storm" h.age = 5 h.color = "Brown" h.color = "Black" h.age += 2
What is the value of the following expressions at the end of execution of the above script?
h.color: | |
h.age: |