Modifying instances inside function
Related code
class Dog: """Represents a dog.""" dog = Dog()
You can write functions that modify objects. For example, set_dog_info
takes a Dog object and two numbers, name
and age, and sets, or overrides if already set,
name
and age
attributes of the dog:
... def set_dog_info(dog, name, age): dog.name = name dog.age = age
Here is an example that demonstrates the effect:
>>> mrk = Dog() >>> mrk.name, mrk.age AttributeError("'Dog' object has no attribute 'name'") >>> set_dog_info(mrk, "Murki", 2) >>> mrk.name, mrk.age ('Murki', 2) >>> set_dog_info(mrk, "Murki", 4) >>> mrk.age 4
update_dog_age
takes a dog and an integer, dage
,
and adds dage
to dog's age:
... def update_dog_age(dog, dage): dog.age += dage dog.name, dog.age = "Murki", 2 update_dog_age(dog, 2) print(dog.age)
4 >>>
Exercises
Write a function, set_student_info(student: Student, name: str, grade: int), and sets name and grade attributes to student.
Write a function, initialize_balance(acc: Account, balance: float), and sets acc's balance attribute.
Write a function, set_building_info(b: Building, floors: int), that sets b's floors attribute.
Write a function, add_floors(b: Building, extra: int), and adds extra to b's floors attribute.
Write a function, set_cat_info(cat: Cat, name: str, age: int, fur_color: str), and sets cat's name, age and fur_color attribute.
class Bottle: """Represents a bottle.""" b1 = Bottle() def set_volume(bottle, volume): bottle.volume = volume def update_volume(bottle): bottle.volume += 3 set_volume(b1, 3) update_volume(b1)
At the end of execution of the above script, what is value of b1.volume?
Exercises
Create a class, Car.
Write a function, set_car_specs(car: Car, model: str, year: int), and sets name and year attributes to car.
Call set_car_specs.
Create a class, Animal.
Write a function, set_animal(animal: Animal, species: str, weight: float), and sets species and weight attributes to animal.
Call set_animal.
Create a class, Circle.
Write a function, set_circle_info(c: Circle, radius: float), and sets c's radius attribute.
Write a function, expand_circle(circle: Circle), and adds 1 to circle's radius.
Create a class, Tree.
Write a function, set_tree_info(tree: Tree, height: float), and sets tree's height attribute.
Write a function, grow_tree(tree: Tree), and adds 2 to tree's height.
class Account: """Represents a bank account.""" acc = Account() def open_account(account, owner, balance): account.owner = owner account.balance = balance def withdraw(account, amount): account.balance -= amount open_account(acc, "Shpresa", 1000) withdraw(acc, 150)
At the end of execution of the above script, what is value of:
acc.owner: | |
acc.balance: |