Python Constructors (def __init__)
In Object-Oriented Programing, a constructor is used to initialise object variables when we create a new object based on a given class. If we had a class called Student with variables Name, Phone, Email, each time we create a new Student object, we need to supply the values of Name, Phone and Email.In Python, we would create such a class as follows:
class Student: def __init__(self, name, phone, email): self.name = name self.phone= phone self.email= email # return statement removed from here
We can create a Student object as follows:
s1=Student("Genghis Khan", "+123456789","Genghis.Khan@gmail.com")
s1=Student("Genghis Khan", "+123456789","Genghis.Khan@gmail.com")
We can acess the object variables of the Student called s1 as follows:
print(s1.name)
print(s1.phone)
print(s1.email)
In IDLE, the program looks as follows:Output:
The keyword "self" refers to the object we have created. Sometimes we have default values for the constructor variables.
No comments:
Post a Comment