lobiclassifieds.blogg.se

Python oop inheritance
Python oop inheritance










python oop inheritance

It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually self for an instance method or cls for a class method - but could be other names) and finding the class (e.g. This only works in Python 3: super()._init_() This works in Python 2 and 3: super(Child, self)._init_() But if you want others to use your code, using super is one thing that allows greater flexibility for users of the code.

Python oop inheritance code#

If you're writing your own code for personal use, you may not care about this distinction. This would mean that you would not call the next _init_ in the MRO, and you would thus not get to reuse the code in it. Without super you would likely hard-code the parent of the class you're writing (like the example does).

python oop inheritance

And those classes could have an _init_ that comes after this _init_ based on the ordering of the classes for method resolution. When another class subclasses the class you wrote, it could also be inheriting from other classes. Super() can enable that sort of architecture. super() makes it easier for other classes to use the class you're writing.Īs Bob Martin says, a good architecture allows you to postpone decision making as long as possible. When you write a class, you want other classes to be able to use it. If the instance is a subclass of this child class, there may be a different parent that comes next in the MRO. Means to call a bound _init_ from the parent class that follows SomeBaseClass's child class (the one that defines this method) in the instance's Method Resolution Order (MRO). What's the difference? SomeBaseClass._init_(self)












Python oop inheritance