Inheritance of Python classes

Source: Internet
Author: User
Tags instance method

Inheritance (inheritance) is a concept in object-oriented software technology. If a category A "inherits from" another category B, it is referred to as the "subcategory of B", and b is referred to as "the parent category of a", or "B is a superclass".

Inheritance allows subclasses to have various properties and methods of the parent category without having to write the same code again. While the subclass inherits the parent category, you can redefine some properties and override some methods that override the parent category's existing properties and methods to get a different function from the parent category. Additionally, appending new properties and methods to subcategories is also a common practice. (From Wikipedia)


From the expression of the upper face inheritance, you can simply summarize the intention or benefit of the inheritance:

1, can implement code reuse, but not just to implement code reuse, sometimes there is no reuse

2. Implement attribute and method inheritance


#!/usr/bin/env python# coding=utf-8__metaclass__ = Typeclass person:def speak (self): print "I love you."    def setheight (self, n): self.length = n def breast (self, n): print ' My breast is: ', nclass Girl (person): def setheight (self): print "The height is:1.70m." if __name__ = = "__main__": Cang = Girl () cang.setheight () Cang.speak () Cang.breast (90)

Save, execute

$ python 20901.py the height is:1.70m. I Love you. My Breast is:90

The above procedure is explained, and the concept and method of inheritance are realized.

A class person is defined first, and three methods are defined in this class. Note that initialization functions are not defined, and initialization functions are not necessary in the class.

Then a class Girl is defined, in parentheses after the name of the class, the name of the previous class, which means that Girl inherits Person,girl as the child of the person, and the person is the parent of the Girl.

Since the person is inherited, Girl has all the methods and attributes in person (although the above example does not list attributes). However, if Girl has a method with the same name as the person, then the same method in person is obscured, showing the method in Girl, which is called the rewrite of the method.

After instantiating the class Girl, executing the instance method Cang.setheight (), because the SetHeight method is overridden in the class Girl, the method in person does not work, and in this instance method the method in class Girl is executed.

Although the Speak method is not seen in class Girl, because it inherits the person, Cang.speak () executes the method in the class person. Similarly Cang.breast (90), they seem to have written these two methods in the class Girl. Now that I've inherited it, it's mine.



Multiple inheritance

The so-called multiple inheritance, is only one class of the parent class, more than one, but multiple. Like what:

#!/usr/bin/env python# coding=utf-8__metaclass__ =  typeclass person:    def eye (self):         print  "Two eyes"     def breast (self, n):         print  "the breast is: ",nclass girl:     age = 28    def color (self):         print  "The girl is white" Class hotgirl (person, girl):     passif __name__ ==  "__main__":     kong = hotgirl ()     kong.eye ()     kong.breast ()     kong.color ()     print kong.age 

In this program, there are two classes: Person and Girl, and then the third class Hotgirl inherits the two classes, notice that the inheritance method is to write the names of the two classes that are inherited in parentheses after the name of the class. But there are no methods in the third class.


Then instantiate the class Hotgirl, since it inherits the two classes above, then the methods of the two classes can be used. Save the program, run it and see

$ python 20902.py eyesthe breast is:90the girl is white28

It is worth noting that this time in class Girl, there is an Age = 28, after the instantiation of Hotgirl, because of the reason of inheritance, this class attribute is also inherited into Hotgirl, so the data can be obtained by instance property Kong.age.


From the above two instances, we have clearly seen the characteristics of inheritance, the method and properties of the parent class are all taken to the subclass; If the subclass overrides the method of the parent class, the child class's method is used, and the parent class is obscured.


Order of multiple inheritance

The order of multiple inheritance is necessary to understand. For example, if a subclass inherits two parent classes, and two parent classes have the same method or property, then after instantiating the subclass, what is the parent class that calls that method or property? To create a program that has no practical meaning, purely to solve the problem:

#!/usr/bin/env python# coding=utf-8class k1 (object):     def foo (self):         print  "K1-foo" Class k2 (object):     def foo (self):        print  "K2-foo"      def bar (self):        print  "K2-bar" class K3 ( Object):     passclass k4 (object):     def foo (self):         print  "K4-foo" class j1 (K1, K2):     passclass j2 (K3, K4):     def bar (self):         print  "J2-bar" Class c (j1, j2):     passif __name__  ==  "__main__":     print c.__mro__    m = c ()     m.fOO ()     m.bar () 

This code, after saving, runs:

[email protected] codes]# python cl.py (<class ' __main__. C ';, <class ' __main__. J1 ';, <class ' __main__. K1 ';, <class ' __main__. K2 ';, <class ' __main__. J2 ';, <class ' __main__. K3 ';, <class ' __main__. K4 ';, <type ' object ' >) k1-fook2-bar

The print c.__mro__ in the code is the order in which the classes are inherited. The order inherits from left to right according to the parent class in C brackets, first J1,J1 's parent class K1,K2. Then to J2, the last J2 of the parent class K3,k4. It's clear from the top. If you want to execute the Foo () method, first look at J1, no, see J2, haven't, see J1 inside of K1, have, namely C==>j1==>j2==>k1;bar () also in this order, in J2 found a.


This order of inheritance properties and method searches is called "breadth first".



Super function

The inheritance of the initialization function is somewhat different from the inheritance of the general method. You can look at the following example:

#!/usr/bin/env python# coding=utf-8__metaclass__ = typeclass person:     def __init__ (self):        self.height =  160    def about (Self, name):         print  "{} is about {}". Format (name, self.height) class girl (person):     def __init__ (self):         self.breast = 90     def about (self, name):         print   "{} is a hot girl, she is about {}, and her  breast is {} ". Format (name, self.height, self.breast) if __name__ == " __main_ _ ":     cang = girl ()     cang.about (" Wangguniang ")

In the above program, class Girl inherits the class person. In class Girl, initialization is set to Self.breast = 90, and as a result of inheriting the person, according to previous experience, the Self.height = 160 in the initializer function of person should also be inherited by Girl. Then, in the about method of rewriting, it is using Self.height.


Instantiate the class Girl, and Execute Cang.about ("Wangguniang"), trying to print out a word wangguniang is a hot Girl, she's about to, and her bereast is 90. Save the program, run it:

$ python 20903.py Traceback (most recent call last): File "20903.py", line A, in <module> cang.about ("Wanggunia ng ") File" 20903.py ", line +, in the about print" {} was a hot girl, she was about {}, and she breast was {} ". Format (name, S Elf.height, Self.breast) attributeerror: ' Girl ' object has no attribute ' height '

Error!


The programmer has a famous saying: Do not seek the best, but ask for error. Error is not a bad thing, we have long experience, is to tell us, then do wrong.


It is important to read the wrong information. Is that we want to print the sentence problem, the error message shows that Self.height is not present. That is, the class Girl does not inherit this attribute from person.


What is the reason? Looking closely at the class Girl, you will find that the __init__ method has been rewritten in addition to the about method that you just emphasized. Don't think of its name as strange, not as a method (function) in a class, it is the same as the __init__ in the class person, and it also overrides the initialization function.


This raises a question. Because a method is overridden in a subclass, the same method in the parent class is obscured. So how do you get the parent class to use this method again? Even if it is covered, it should still exist, do not waste it.


There is a method in Python that is advocated: the Super function.

#!/usr/bin/env python# coding=utf-8__metaclass__ = typeclass person:     def __init__ (self):        self.height =  160    def about (Self, name):         print  "{} is about {}". Format (name, self.height) class girl (person):     def __init__ (self):         super (Girl, self). __ init__ ()         self.breast = 90    def  about (self, name):        print  "{} is a  hot girl, she is about {}, and her breast is {} ". Format (name, self.height, self.breast)         super (Girl,  self). About (name) If __name__ ==  "__main__":     cang = girl ()     cang.about ("Wangguniang")

In the subclass, the __init__ method overrides, in order to call the parent-like method, use Super (Girl, self). __init__ () way. The parameters of the Super function, the first one is the class name of the current subclass, the second is self, then the dot, and the dot is followed by the method of the parent class to be called. It is also possible to invoke the about method of the parent class in the About method that the subclass overrides.


Execution Result:

$ python 20903.py Wangguniang is a hot girl, she's about 160


Inheritance of Python classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.