Sep-01-2021, 05:40 PM
(This post was last modified: Sep-01-2021, 06:01 PM by snippsat.
Edit Reason: Added code tag
)
Hello Forum,
We can create a class and include, at the very beginning, the __init__ special method called the constructor which can be parametrized or not. The __init__ method is called anytime an object is created: it constructs objects. The name __init__ stands for initialization because it sets the attributes/methods that every object will have. However, initialization in this case does not mean assigning a specific value to the attributes....Within the class definition, the constructor refers to the specific attributes and methods using the argument self. Self indicates all potential and future instances of the class.
That said, we can also create a class without including the constructor __init__ and still create attributes that all objects will haves...What happens it we don't include the __init__ method? We don't get an error: the __init__ special method is automatically called anyway as the "default constructor". So what is the point of explicitly including __init__ into the class definition if it works by itself anyway?
I have seen the following example:
We can create a class and include, at the very beginning, the __init__ special method called the constructor which can be parametrized or not. The __init__ method is called anytime an object is created: it constructs objects. The name __init__ stands for initialization because it sets the attributes/methods that every object will have. However, initialization in this case does not mean assigning a specific value to the attributes....Within the class definition, the constructor refers to the specific attributes and methods using the argument self. Self indicates all potential and future instances of the class.
That said, we can also create a class without including the constructor __init__ and still create attributes that all objects will haves...What happens it we don't include the __init__ method? We don't get an error: the __init__ special method is automatically called anyway as the "default constructor". So what is the point of explicitly including __init__ into the class definition if it works by itself anyway?
I have seen the following example:
Class Animal : type = "Carnivorous" name = "lion" def show_output(self): print("A" + self.name "is a" self.type) # Create an instance and call the method a_lion = Animal() a_lion.show_output()thanks!