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
nameshould be"Abbey" - Property
ageshould be30
- Property
Person("Eric", 40)should create an object with the below properties- Property
nameshould be"Eric" - Property
ageshould be40
- Property
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules