In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what are the single inheritance knowledge points of the Python class". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the single inheritance knowledge points of the Python class".
I. inheritance of classes
One of the three object-oriented elements, inheriting Inheritance
Both humans and cats inherit from animals.
Individuals inherit from their parents and inherit some of the characteristics of their parents, but they can also have their own personality.
In the object-oriented world, inheriting from the parent class, you can directly have the properties and methods of the parent class, so you can reduce the code and take more. Subclasses can define their own properties and methods
Class Animal: def _ _ init__ (self Name): self._name = name def shout (self): print ("{} shouts" .format (self.__class__.__name__)) @ property def name (self): return self._name class Cat (Animal): pass class Dog (Animal): pass a = Animal ("monster") a.shout () # Animal shouts cat = Cat ("garfield") Cat.shout () # Cat shoutsprint (cat.name) # garfield dog = Dog ("ahuang") dog.shout () # Dog shoutsprint (dog.name) # ahuang
In the above example, we can see that the properties and methods of the parent class are directly inherited by inheriting, cats and dogs without writing code.
Inheritance:
The form of class Cat (Animal) inherits from the parent class, with a list of inherited classes written in parentheses.
Inheritance allows subclasses to acquire features (attributes, methods) from the parent class.
Parent class:
Animal is the parent class of Cat, also known as base class and superclass.
Subcategory:
Cat is a subclass of Animal and becomes a derived class.
Second, the definition of inheritance, viewing the special properties and methods of inheritance
Format
Class subclass (base class 1 [, base class 2, …]) Statement block
If a class is defined without a list of base classes, it is equivalent to inheriting from [object]. In Python3, the [object] class is the base class for all objects
View inherited special properties and methods
Example of special attribute meaning the base class of the _ _ base__ class
Base class tuple of _ _ bases__ class
_ _ mro__ display method search order, tuple of the base class
Mro () is the same as the subclass list of int.mro () _ subclasses__ () class int.__subclasses__ () 3. Access control in inheritance class Animal: _ _ COUNT = 100HEIGHT = 0 def _ init__ (self,age,weight) Height): self.__COUNT + = 1 self.age = age self.__weight = weight self.HEIGHT = height def eat (self): print ("{} eat" .format (self.__class__.__name__)) def _ _ getweight (self): print (self.__weight) @ classmethod def showcount1 (cls): print (cls. _ _ COUNT) @ classmethod def _ _ showcount2 (cls): print (cls.__COUNT) def showcount3 (self): print (self.__COUNT) class Cat (Animal): NAME = "CAT" _ _ COUNT = 200 # a = Cat () # TypeError: _ _ init__ () missing 3 required positional arguments: 'age' 'weight' And 'height'a = Cat # Cat eatprint (a.HEIGHT) # 15#print (a.__COUNT) # AttributeError:' Cat' object has no attribute'_ COUNT'#print (a.__showcount2) # AttributeError: 'Cat' object has no attribute' _ showcount2'#print (a.__getweight) # AttributeError: 'Cat' object has No attribute'_ getweight'a.showcount3 () # 101a.showcount1 () # 100print (a.NAME) # CAT print (Animal.__dict__) # {'_ module__':'_ _ main__' '_ Animal__COUNT': 100,' HEIGHT': 0,'_ _ init__':, 'eat':,' _ Animal__getweight':, 'showcount1':,' _ Animal__showcount2':, 'showcount3':,' _ dict__':,'_ _ weakref__': '_ _ doc__': None} print (Cat.__dict__) # {' _ _ module__':'_ _ main__', 'NAME':' CAT','_ Cat__COUNT':,'_ _ doc__': None} print (a. Animal__COUNT': 30,'_ Animal__weight': 50, 'HEIGHT': 15})
If you inherit from the parent class and do not have it, you can find it in the parent class.
Private ones are inaccessible, but in essence, the name is still changed and put in the class [_ _ dict__] of this attribute, knowing that the achievement of the new people can directly find the hidden variable. This is a dark magic to be used with caution.
Summary
When inheriting, the common, subclasses and instances can be accessed at will; private members are hidden, subclasses and instances cannot be accessed directly, and the private variable can be accessed in the method within the class where the private variable resides
Python implements the same object-oriented inheritance mechanism as other languages through its own set of implementation.
Attribute search order: instance [_ _ dict__]-class [_ _ dict__]-parent class [_ _ dict__]
If no exception is found after searching these places, find it first and return immediately.
Fourth, the rewriting of methods, Override overrideclass Animal: def shout (self): print ("Animal shouts") class Cat (Animal): def shout (self): print ("miao") a = Animal () a.shout () # Animal shoutsb = Cat () b.shout () # miao print (a. Print (Animal.__dict__) # {'_ _ module__':'_ _ main__' 'shout':,'_ _ dict__':,'_ _ weakref__':,'_ _ doc__': None}
Why doesn't shout in the Cat class have a method to print shout in Animal? the method is overwritten?
This is because the attribute lookup order: instance's [_ _ dict__]-class's [_ _ dict__]-parent class [_ _ dict__]
How does that subclass print the same fate method of the parent class
Super () can access the properties of the parent class
Class Animal: def shout (self): print ("Animal shouts") class Cat (Animal): def shout (self): print ("miao") def shout (self): print ("super ():", super () print (super (Cat, self)) super (). Shout () super (Cat) Self) .shout () # is equivalent to super () .shout () self.__class__.__base__.shout (self) # A = Animal () a.shout () # Animal shoutsb = Cat () b.shout () # super (): # # Animal shouts # Animal shouts # Animal shoutsprint (a. Module__': module__': _) # {} print (b. Roommates) # {} print (Animal.__dict__) # {'_ _ module__':'_ _ main__' 'shout':,' _ _ dict__':,'_ _ weakref__':,'_ _ doc__': None} print (Cat.__dict__) # {'_ _ module__':'_ main__', 'shout':,' _ _ doc__': None}
Super (Cat,self). Shout () is equivalent to
Call the method of shout in the base class of the cat class in the current instance of b
Does that apply equally to class methods and static methods?
Class Animal: @ classmethod def class_method (cls): print ("class_method") @ staticmethod def static_method (): print ("static_methond_animal") class Cat (Animal): @ classmethod def class_method (cls): super (). Class_method () # class_method print ("class_method_cat") @ staticmethod def static_method (cls,self): super (Cat) Self) .static_method () print ("static_method_cat") b = Cat () b.class_method () # class_method # class_method_catb.static_method (Cat,b) # static_methond_animal # static_method_cat
These methods can be covered, the principle is the same, the search order of attribute dictionaries
5. Initialization in inheritance
Look at the following code to see if there is any problem.
Class A: def _ _ init__ (self,a): self.a = a class B (A): def _ init__ (self,b,c): self.b = b self.c = c def printv (self): print (self.b) print (self.a) a = B (100300) print (a. A.printv: 300} print (a.classrooms classrooms. Classrooms basesystems _) # (,) a.printv () # 100 # AttributeError: 'B'object has no attribute 'a'
The above example code
If class B is defined and declared to inherit from class A, you can see class An in class B in _ _ bases__
This and whether to call the constructor of class An are two different things.
If the constructor of An is called in B, you can have the properties of the parent class, if you understand this sentence?
Class A: def _ _ init__ (self,a): self.a = a class B (A): def _ _ init__ (self,b,c): super (). _ _ init__ (Benec) # A.roominiture _ (self) Benec) self.b = b self.c = c def printv (self): print (self.b) print (self.a) a = B (100300) print ) a.printv () # 100 # 400
As a good habit, if the parent class defines a _ _ init__ method, you can call it in the subclass _ _ init__ instead [it is recommended that the super () method call be applied]
When does the subclass automatically call the parent class's [_ _ init__] method?
Example 1: [initialization of B instance automatically calls the _ _ init__ method of base class A]
Class A: def _ _ init__ (self): self.a1 = "A1" self.__a2 = "a2" print ("An init") class B (A): pass b = B () # An initprint (b.A1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Example 2: [the initialization _ _ init__ method of B instance does not automatically call the initialization _ _ init__ method of the parent class, it needs to be called manually]
Class A: def _ _ init__ (self): self.a1 = "A1" self.__a2 = "a2" print ("An init") class B (A): def _ _ init__ (self): self.b1 = "b1" self.__b2 = "b2" print ("b init") # A.roominitcake _ (self) b = B () # b initprint (b.roommates thanks _) # {'b1': 'b1' '_ Baking B2B2:' b2'}
So how to instantiate correctly?
Note that calling the _ _ init__ method of the parent class appears in different locations, which may result in different results
Class Animal: def _ _ init__ (self,age): print ("Animal init") self.age = age def show (self): print (self.age) class Cat (Animal): def _ init__ (self,age,weight): # the order in which the _ _ init__ method of the parent class is called determines the result of the show method super (Cat Self). _ init__ (age) print ("Cat init") self.age = age + 1 self.weight = weight a = Cat (10L5) a.show () # Animal init # Cat init # 11
How to directly change all the instance properties in the above example to private properties?
The solution, a principle, one's own private properties, should be read and modified by your own methods, without resorting to the methods of other classes, that is, parent classes or derived classes.
Class Animal: def _ _ init__ (self,age): print ("Animal init") self.__age = age def show (self): print (self.__age) class Cat (Animal): def _ init__ (self,age,weight): # the order in which the _ _ init__ method of the parent class is called determines the result of the show method super (Cat Self). _ init__ (age) print ("Cat init") self.__age = age + 1 self.__weight = weight def show (self): print (self.__age) a = Cat (10L5) a.show () # Animal init # Cat init # 11print '_ Cat__age': 11,' _ Cat__weight': 5} Thank you for your reading The above is the content of "what are the single inheritance knowledge points of the Python class?" after the study of this article, I believe you have a deeper understanding of what the single inheritance knowledge points of the Python class have, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.