Now, all we need is to use _init_ to initialize our class’s attributes ( name and roll). Note that like every other method defined in a class, the _init_ method too needs “self” as its first parameter. Let’s add _init_ to a class Student that has two attributes, name and roll number.įor now, let the _init_ method be empty with just a pass statement inside it (we’ll add some behavior just in a moment). This special method, or as we like to call in Python, this “ magic method” is the _init_ method. We said in the last section that a special method is responsible for assigning values to attributes of an object. So we now know the “why”, let’s move on to the “ how”! Coding Constructors So all you need a constructor for is attribute initialization. assigning values to the attributes for that object).īut in Python, the interpreter automatically handles the object instantiation part. creating a new object) and attribute initialization (i.e. In other OOP languages, a constructor is a special method that is responsible for both object instantiation (i.e. In object-oriented programming, “ constructors” take care of this situation. The bottom line is, no matter where you use variables in Python, you have to initialize them with a starting value.īut the question here is: how do we do this for a new object created from a class? Say no more interpreters! We’ll define ‘y’ too for you. The interpreter complains again! This time it says ‘y’ is not defined.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |