vefhu.blogg.se

Super in oop python
Super in oop python









gasĬlass Truck ( Veichle ) : def _init_ ( self, price, color, tires ) : super ( ). gas = 0 def gasLeft ( self ) : return self. class Veichle : def _init_ ( self, price, color ) : self. speak ( ) # This will print "I am a Dog" Exampleīelow is a realistic example of inheritance and where you may use it. _init_ ( name, age ) # This will call the Animal classes constructor method def speak ( self ) : print ( "I am a Dog" ) tim = Dog ( "Tim", 5 ) tim. age, "years old" ) class Dog ( Animal ) : def _init_ ( self, name, age ) super. name = nameĭef speak ( self ) : print ( "I am", self. class Animal ( ) : def _init_ ( self, name, age ) : self. If we create a method or attribute inside of our child class with the same name as one in the parent it will override the parent class. Sometimes when we inherit from a parent class we want to have methods or attributes that have the same name as a method in the parent class but that have a different functionality. speak ( ) # This will print "I am Tim and I am 5 years old" Overriding Methods _init_ ( name, age ) # This will call the Animal classes constructor method tim = Dog ( "Tim", 5 ) tim. age, "years old" ) class Dog ( Animal ) : def _init_ ( self, name, age ) super ( ).

super in oop python

#Super in oop python code#

To save ourselves from repeating code we can call the parents init function from inside of our childs class init like so: class Animal ( ) : def _init_ ( self, name, age ) : self. Often times when we create sub-classes we want to initialize them in a similar same way as the parent class.

super in oop python

speak ( ) # This will print "I am Tim and I am 5 years old" Calling a Super-Classes Constructor type = "dog" # Since we inherit from the animal class we can use the method speak on Dog objects tim = Dog ( "Tim", 5 ) tim. age, "years old" ) class Dog ( Animal ) : def _init_ ( self, name, age ) self. When we inherit from a class all the methods and attributes of the parent class are passed down to the child class. The following words are all equivalent and mean a class that is inherited from:

super in oop python

The following words are all equivalent and mean a class that inherits from another: This allows us to create a variety of different sub-classes or child classes based off of what is known as a parent class or super class. When we create classes we can inherit methods and attributes from other already existing classes.









Super in oop python