criticlooki.blogg.se

Python oop inheritance
Python oop inheritance




python oop inheritance

PYTHON OOP INHERITANCE UPDATE

Let’s update our vehicle.py file: class Vehicle:ĭef _init_(self, make, model, fuel="diesel"): We can, of course, use a subclass to override variables that belong to a parent class.

python oop inheritance

Behold: > from vehicle import Vehicle, Car Don’t forget to import your Vehicle and Car classes. Note that even though the variables are stored at the Vehicle level, they are instance variables because self is bound to my_car, which is a Car, which is a Vehicle. In _init_(), we call super()._init_(), which resolves to our parent class, Vehicle, and runs its _init_ function, where the variables are stored. When we instantiate a Car instance, the interpreter calls _init_(), where we pass in two arguments ( make and model) and an optional 3rd ( fuel, which defaults to “gas”). class Vehicle:ĭef _init_(self, make, model, fuel="gas"): In a file called vehicle.py, let’s create a parent Vehicle class, and have our Car class be a subclass. We can do the same with our own classes, too.

python oop inheritance

Objects that belong to classes that are higher up in the hierarchy (more generic) are accessible by subclasses, but not vice versa.Įarlier, we saw that bool is a subclass of int, thus, it inherited the properties and methods of the int class, and then extended it to be more specific to booleans. Inheritance makes it possible to break up and organize your code into a hierarchy, from generic to specific. The course content is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.Ĭlass inheritance is a very useful Object-oriented Programming construct for sharing and reusing code.






Python oop inheritance