The principles of inheritance in Python

Source: Internet
Author: User

inheritance is one of the important characteristics of object-oriented, and inheritance is a parent-child relationship between two classes or multiple classes, which inherits all the public instance variables and methods of the parent process. Inheritance implements the reuse of code. Reuse existing data and behavior, reduce code rewriting, Python represents the inheritance relationship with a pair of parentheses after the class name, the class in parentheses represents the parent class, and if the parent class defines the __init__ method, the child class must display the __init__ method of the parent class. If the subclass needs to extend the behavior of the parent class, you can add arguments to the __init__ method. The following shows the implementation of the inheritanceclass Fruit:def __init__ (self, color):Self.color = Colorprint "Fruit ' s Color:%s"%self.colordef Grow (self):print "Grow ..."class Apple (Fruit): #继承了父类def __init__ (self, color): #显示调用父类的__init__方法fruit.__init__ (self, color)print "Apple's color:%s"% Self.color class Banana (Fruit): #继承了父类def __init__ (self, color): #显示调用父类的__init__方法fruit.__init__ (self, color)print "Banana ' s color:%s"%s Self.color def Grow (self): #覆盖了父类的grow方法print "Banana grow ..."if __name__ = = "__main__":Apple = apple ("Red")Apple.grow ()banana = Banana ("yellow")Banana.grow ()Output Result:Fruit ' s color:redApple ' s color:redGrow ...Fruit ' s color:yellowBanana ' s Color:yellow
Banana Grow ... simulation of abstract classesAbstract class is an abstraction of the characteristics and behavior of a class of things, and abstract classes are composed of abstract methods. PYTHON2.5 does not provide the syntax for abstract classes, and the characteristics of abstract classes cannot be instantiated, but abstract classes can be simulated by Python's Notimplementederror class, notimplementederror classes inherit from Python runtime error classes RuntimeError 。 When an abstract class is instantiated, an exception is thrown. simulating the implementation of abstract classesdef Abstract (): #定义了全局函数Raise Notimplimentederror ("abstract"):         class Fruit:def __init__ (self):if self.__class__ is Fruit: #如果实例化的类是Fruit, throws an exceptionabstract ()print "Fruit ..."class Apple (Fruit):def __init__ (self):fruit.__init__ (self)print "Apple ..." if __name__ = = "__main__":Apple = apple () #输出: Fruit AppleAlso , Python does not provide support for interfaces. An interface is a special abstract class that has no data members, but a set of methods that are not implemented. ---------------------------------------------------------------

As long as it involves object-oriented, "class" is a synonym that must appear.

Classes and objects are the two main aspects of object-oriented programming. class creates a new type, and the object is an instance of this class.

Some concepts of the class:

Including the initialization method __init__, can be understood as constructs, self, understood as this, and so on in the previous article introduced, now learn the inheritance of classes.

Inherited:

One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.

What to note: Inherit the syntax class derived class name ( base class name )://... The base class name is written in parentheses, and the base class is specified in the tuple at the time the class is defined. This is different from C #.

When to use inheritance: if I need to define a few classes, and there are some common properties and methods between classes and classes, then I can use the same properties and methods as members of the base class, and special methods and properties are defined in this class, so that only inherit the base class this action, you can access the properties and methods of the base class, It improves the extensibility of the code.

There are pros and cons to everything: one weakness of inheritance is that there may be special classes and other special places, and a class can be defined, and the class may be defined under it, which will cause the inherited line to grow longer, and with inheritance, any small change needs to redefine a class, which can easily cause explosive growth of the class. , producing a whole bunch of sub-categories that are slightly different. So there is a "multi-use combination less inheritance" principle, (I think the use of the two is the best bar *^◎^*)

Some of the characteristics of inheritance in Python:

1: The construction of the base class in inheritance (The __init__ () method) is not automatically called, it needs to be called specifically in the construction of its derived class. different from C #

2: When calling a method of the base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument

3:python always looks for a method of the corresponding type first, and if it cannot find the corresponding method in the derived class, it begins to look in the base class one by one. (Find the method that was called in this class before you can find it in the base class).

If more than one class is listed in an inheritance tuple, it is called "Multiple inheritance."

Example: Define a module in which a base class is defined:

Sub-class:

Output:

If you do not use the __init__ () initialization function in a subclass, the subclass inherits the properties of the base class, such as:

Output:

The principles of inheritance in Python

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.