Editor settings

General settings

Save settings

Learn to program with Python

Setting objects' properties with methods #

Instead of setting an object's property directly, it is more common and preferred to set or change the properties with an object's method.

For example, instead of setting the brand property of a Car object like this:

car.brand = "Toyoto"

We could add a method to set the brand property, and call that method instead:

class Car:
   def set_brand(self, brand):
        self.brand = brand

car = Car()
car.set_brand("Toyoto")
print(car.brand) # Output: Toyoto

When the code self.brand = brand is executed, since self is the object calling the method, it is equivalent to running the code car.brand = brand.

Required properties #

One very common way to set an object's properties is with the __init__ method. Instead of allowing the Car object to be created without the brand property, we can make it required so that all cars have this property, like so:

class Car:
    def __init__(self, brand):
        self.brand = brand

toyoto = Car("Toyoto")
honde = Car("Honde")

print(toyoto.brand) # Output: Toyoto
print(honde.brand) # Output: Honde

Exercise #

  • With the given class Person, update the __init__ method so that the construction input is set as the object's properties.

Tests #

  • Person("Abbey", 30) should create an object with the below properties
    • Property name should be "Abbey"
    • Property age should be 30
  • Person("Eric", 40) should create an object with the below properties
    • Property name should be "Eric"
    • Property age should be 40
Output will be displayed here