In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the Python class of multi-inheritance knowledge of what the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that you read this Python class of multi-inheritance knowledge points which articles will have a harvest, let's take a look at it.
1. Different versions of Python classes
Python2.2 did not have a common ancestor before, and then introduced the Object class, which is the common ancestor class Object of all classes.
Python2 is divided into classical (old-style) and new-style classes for compatibility.
Python3 is full of new classes.
New classes inherit from Object, and new classes can use super
# Classical class runs class An in python2.x: pass print (dir (A)) # ['_ doc__','_ module__'] print (A. classical classrooms) # () a = A () print (a.classical classrooms _) # _ _ main__.A print (type (a)) #
New class
# New class runs class B: pass print (dir (B)) in python3.x # [_ _ class__','_ _ delattr__','_ _ dict__','_ _ dir__','_ _ doc__','_ eq__','_ format__','_ ge__','_ getattribute__','_ _ gt__','_ _ hash__' '_ _ init__',' _ _ init_subclass__','_ _ le__','_ _ lt__','_ _ module__','_ _ ne__','_ _ new__','_ _ reduce__','_ _ reduce_ex__','_ _ repr__','_ setattr__','_ sizeof__','_ str__','_ _ subclasshook__' '_ weakref__'] print (B. inheritance basesinherit _) # (,) B = B () print (B.The classrooms _) # print (type (B)) # II. Multiple inheritance
OCP principle: use "inheritance" more and modify less
The purpose of inheritance: to enhance the base class and implement polymorphism
Polymorphisms
In object-oriented, parent classes and subclasses are linked together through inheritance. If they can be realized through a set of methods, they can be realized differently, that is, polymorphism.
If a class inherits from multiple classes, it will have the characteristics of multiple classes.
III. Drawbacks of multi-inheritance
Multi-inheritance is a good simulation of the world, because transactions rarely inherit single, but abandoning simplicity inevitably introduces complexity and brings conflict.
Just as a child inherits the characteristics from both parents, do his eyes look like his father or his mother? Who does the child look like a little more?
The implementation of multi-inheritance will increase the complexity of compiler design, so now many languages abandon the multi-inheritance of classes.
C++ supports multi-inheritance; Java abandons multi-inheritance
In Java, a class can implement multiple interfaces, and an interface can inherit multiple interfaces. The interface of Java is very pure, it is just a method declaration, and the inheritor must implement these methods and have these capabilities to do what he or she can do
Multiple inheritance may lead to ambiguity. For example, both cats and dogs inherit from animals. Now that one class inherits more cats and dogs, both cats and dogs have shout methods. Whose shout does the subclass inherit?
Solution: achieve a multi-inherited language, to solve ambiguity, depth first or breadth first
4. Python multi-inheritance implementation class ClassName (base class list): class body
The problem of path selection caused by multi-inheritance is that which parent class inherits the characteristics of the parent class?
Breadth first or depth first?
Python uses MRO (method resolution order) to solve the class search order problem.
Classic algorithm, defined from left to right, depth-first strategy [e.g. MRO algorithm before Python2.2, left graph, MyClass → D → B → A → C → A]
The new class algorithm, the upgrade of the classical algorithm, repeats only the last one. [the MRO on the left is: MyClass → D → B → C → A → object]
The C3 algorithm, when the class is created, calculates a MRO ordered list. [the only algorithm supported by Python3, MRO in the left is MyClass → D → B → C → A → object] C3 is too complex to remember, we just have to remember [object.mro (), show the inherited method, look it up from left to right]
Fifth, the shortcomings of multi-inheritance
When there are many classes and inheritance is complex, it is difficult to tell what kind of inheritance path there are too many inheritance paths.
Team collaborative development, if the introduction of multiple inheritance, then the code will be uncontrollable
Whether or not the programming language supports multiple inheritance, multiple inheritance should be avoided.
Pythond's object-oriented, we see that it is too flexible and open, so the team should obey the rules.
VI. Mixin
Class has the following inheritance relationship
The document Document class is the abstract base class of all other document classes, and the Word and PDF classes are subclasses of Document.
Requirements: provide printing ability ideas for document subclasses:
1. Provide print method in Document
Class Document: def _ init__ (self,content): self.coutent = content def print (self): print (self.coutent) class Word (Document): pass class Pdf (Document): pass a = Word ("tom com") a.print () # tom com
The method provided by the base class is not implemented because it may not be suitable for the printing of the subclass, and the subclass needs to be overridden.
Print is a kind of ability-printing function, which is not required by all subclasses of Document, so it's a bit of a problem from this point of view.
Class Document: def _ _ init__ (self,content): self.coutent = content def print (self): print (self.coutent) class Word (Document): def print (self): print ("Word print {}" .format (self.coutent)) class Pdf (Document): pass a = Word ("tom com") a.print () # Word print tom com
Idea 2: add to the subclasses that need to be printed
If it is added directly to the existing subclass, it violates the OCP principle, so it should be added after inheritance.
Class Document: # it is not allowed to modify def _ _ init__ (self Content): self.coutent = content def print (self): print (self.coutent) class Word (Document): pass # does not allow modification of class Pdf (Document): pass # does not allow modification of class PrinttableWord (Word): def print (self): print ("PrinttableWord print {}" .format (self.coutent) print (PrinttableWord.mro ()) # [, ] a = PrinttableWord ("tom com") a.print () # PrinttableWord print tom com
Looks good, if you have to provide other similar capabilities, how to inherit?
When applied to the network, documents should have the ability to serialize, and serializability should be implemented on the class. Serializability may also be divided into using pickle, josn, messagepack, etc.
At this time, I found that there may be too many classes, and the way of inheritance is not very good.
There are too many functions, Class A needs some functions, Class B needs several other functions, which is very tedious
Idea 3: decorator, enhance a class with decorator and add function to the class. If that class needs it, decorate it.
Def printable (cls): def _ print (self): print ("_ print decorator {}" .format (self.coutent)) return _ print cls.print = _ print return cls class Document: def _ init__ (self,content): self.coutent = content def print (self): print (self.coutent) class Word (Document): pass class Pdf (Document): pass @ printableclass PrinttableWord (Word): pass # inherit first Print (PrinttableWord.__dict__) # {'_ module__':'_ main__','_ doc__': None, 'print':} a = PrinttableWord ("tom") a.print () # _ print decorator tom
Advantages: simple and convenient, dynamically increase where needed
Idea 4: Mixin [inherits with classes]
Look at the code first.
Class PrintableMixin: def print (self): print ("PrintableMixin {}" .format (self.coutent)) class Document: def _ init__ (self,content): self.coutent = content def print (self): print (self.coutent) class Word (Document): pass class Pdf (Document): pass class PrinttableWord (PrintableMixin,Word): pass print (PrinttableWord.mro ()) # [, ] print (PrinttableWord.__dict__) # {'_ module__':'_ main__','_ doc__': None} a = PrinttableWord ("tom") a.print () # PrintableMixin tom
Mixin is a mix of other classes, bringing in the properties and methods of the class
Here, it seems that the Mixin class has the same effect as the decorator, but Mixin is a class and can be inherited and enhanced.
Class PrintableMixin: def print (self): print ("PrintableMixin {}" .format (self.coutent)) class Document: def _ init__ (self,content): self.coutent = content def print (self): print (self.coutent) class Word (Document): pass class Pdf (Document): pass class PrinttableWord (PrintableMixin,Word): pass class SuperPrintableMixin (PrintableMixin) Word): def print (self): print ("~" * 30) super (SuperPrintableMixin, self). Print () print ("~" * 30) print (SuperPrintableMixin.mro ()) # [,] print (SuperPrintableMixin.__dict__) # {'_ module__':'_ main__', 'print': '_ doc__': None} a = SuperPrintableMixin ("tom") a.print () # ~ # PrintableMixin tom # ~ 7, mix class
Minxin is essentially implemented by multi-inheritance.
Mixin embodies a combined design pattern.
In object-oriented design, a loaded class often requires a lot of functions, and these functions are provided by different classes, which requires a lot of classes to be combined.
From the design pattern point of view, more combinations, less inheritance.
Principles for using the Mixin class
The _ _ init__ initialization method that should not be displayed in the Mixin class
The Mixin class usually does not work independently because it is a partial functional implementation that is ready to be mixed into other classes
The ancestor class of the Mixin class should also be the Mixin class
When used, the Mixin class is usually in the first place in the inheritance list, for example: class PrintableWord (PrintableMixin,Word): pass
This is the end of this article on "what are the multi-inheritance knowledge points of the Python class?" Thank you for reading! I believe you all have a certain understanding of "what are the multi-inheritance knowledge points of Python". If you want to learn more knowledge, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.