Tutorial: Object Oriented Programming in Python – Part 2
Posted by Ed on December 6, 2011
This is the follow-up to the tutorial on object oriented programming in Python. I describe how to assign values to the attributes by using the __init__method().
Last time we created an object of the Person class by using:
p = Person()
We call Person() the constructor of the Person class because it creates an object and assigns it to the variable p. Afterwards, we assigned a name and an age to p:
Here, we used the methods setName() and setAge() to choose values for the attributes name and age. However, we often want to assign these attributes already when creating an object. This can be done with the __init__() method.
class Person2: # attributes name = "No name yet" age = 0 # methods def __init__(self,x,y): self.name = x self.age = y print("You have just created a Person object.") def talk(self): print("Hi! My name is", self.name, "and I am", self.age, "years old.")
Copy the code above in a file person2.py and run the file, e.g. in IDLE go to Run -> Run Module or simply press F5. The code represents the Person2 class. Afterwards go to the Python-Shell and type the following:
>>> p = Person2("Sandy", 34) You have just created a Person object. >>> p.talk() Hi! My name is Sandy and I am 34 years old.
In line 1 you have used the constructor Person2(). Note that the constructor always has the same name as the class. And unlike before, we have written something inside the brackets, namely “Sandy” and 34. By doing so, we tell our object to have the name “Sandy” and the age 34.
In line 3 we let the person talk to check whether the name and age have been set correctly. The values have been assigned correctly without using a setName() and setAge() method.
Keep the following in mind: Everytime we use the constructor Person2() the __init__() method is called. Have a look again what the __init__method() does. It assigns x to self.name and y to self.age, i.e. it initializes the attributes.
We can extend our class by the attributes food and music:
class Person2: # attributes name = "No name yet" age = 0 food = "No favorite food yet" music = "No favorite music yet" # methods def __init__(self,x,y): self.name = x self.age = y print("You have just created a Person object.") def talk(self): print("Hi! My name is", self.name, "and I am", self.age, "years old.") def setFoodAndMusic(self, x, y): self.food = x self.music = y def tellMore(self): print("I like eating", self.food, "and I love listening to", self.music)
The setFoodAndMusic() method allows us to assign values to the attributes food and music. Run the code above and type the following in the Python-Shell:
>>> q = Person2("Linda", 21) You have just created a Person object. >>> q.setFoodAndMusic("Spaghetti", "Jazz") >>> q.talk() Hi! My name is Linda and I am 21 years old. >>> q.tellMore() I like eating Spaghetti and I love listening to Jazz
In summary, there are two ways to assign values to the attributes:
(i) We use the constructor that calls the __init__method().
(ii) We add methods to our class that allow us to set values for the attributes.
Create a person whose name is “Charlie”. Charlie is 52 years old and loves Pizza and classical music. Afterwards, use the talk() and tellMore() methods as check.
Consider the Car class from the last tutorial. Write a new class Car2 with an __init__method() which initializes the attributes brand and maxSpeed.
Additionally add two more attributes: wiper and currentSpeed. Add a method setWiperAndSpeed() to set values for these attributes. Write a printMore() method to check values.
Solution to Exercise 1:
>>> r = Person2("Charlie", 52) You have just created a Person object. >>> r.setFoodAndMusic("Pizza", "classical music") >>> r.talk() Hi! My name is Charlie and I am 52 years old. >>> r.tellMore() I like eating Pizza and I love listening to classical music
Solution to Exercise 2:
The Car2 class could look like this:
class Car2: # attributes brand = "No brand yet" maxSpeed = 0 wiper = "off" currentSpeed = 0 # methods def __init__(self,x,y): self.brand = x self.maxSpeed = y def printData(self): print("The car was manufactured by", self.brand, ",") print("and its maximum speed is", self.maxSpeed, "km/h.") def setWiperAndSpeed(self,x,y): self.wiper = x self.currentSpeed = y def printMore(self): print("The wiper is turned", self.wiper, "and the current speed is", self.currentSpeed, "km/h.")
Run the car2.py file and type the following in the Python-Shell:
>>> myCar = Car2("Audi", 150) >>> myCar.setWiperAndSpeed("on", 60) >>> myCar.printData() The car was manufactured by Audi , and its maximum speed is 150 km/h. >>> myCar.printMore() The wiper is turned on and the current speed is 60 km/h.