The three main features of Python object-oriented

Source: Internet
Author: User

Inherited

Let's look at a simple example to learn about inheritance.

classAnimal:#Parent Class    def __init__(self, name, age, Department): Self.name=name Self.age=Age self.department=Departmentdefrunning (self):Print('%s can run! '%self.name)classCat (Animal):#the parent class to inherit in parentheses    def __init__(self, name, age, Department, tail): Animal.__init__(Self, name, age, Department)#that is, if you want to use the property of the parent class and have its own unique property, call the parent class's __init__ internally .Self.tail = Tail#Derived PropertiesclassMouse (Animal):def __init__(self, name, age, Department, tail): Super ().__init__(name, age, Department)#The Super method only has the equivalent of animal.__init__ (self, name, age, department) in Python3Self.tail =TailclassHuman (Animal):def __init__(self, name, age, Department): Animal.__init__(self, name, age, Department)defCreate (self):#Derivation Method        Print('%s can be created! '%self.name) Cat= Cat ('Tom', 10,'Cat Department','Blue Tail') Mouse= Mouse ('Jerry', 7,'Rat Section','Grey Tail') Human= Human ('Zzy', 24,'Human Subjects')Print(Cat.name)#TomPrint(Mouse.tail)#Grey TailCat.running ()#Tom can run! Human.create ()#Zzy can be created! Print(Human.mro ())#[<class ' __main__. Human ';, <class ' __main__. Animal ';, <class ' object ';] View inheritance OrderPrint(Human.__bases__)#<class ' __main__. Animal ' > View all inherited parent classes
Inheritance

Summarize the inherited features using the example above:

"""     Inheritance: Subclasses are the relationships of the parent class  : You can reduce the repetition of code    through the class name (the parent class name) to inherit,    a class can be single-inheritance or can inherit    a class can be inherited by a single class, or can be inherited    by multiple classes The parent class does not have a property in the child class and the parent class is not in the derived property,                          and some methods in the subclass inherit from the derived method    : When the        object is called, it is found in the subclass, there must be a subclass in the subclass, and no more inheritance is found in the parent class    :        In modern classes (all of which are new in Python3), object invocation lookup is to find the        new class by breadth, inherit object by default        in the classic class, object invocation lookup is the depth lookup of the        Classic class, Default class created by python2.7, inherits object and becomes modern class " " "

Consider the inheritance lookup order: Here take Python3 as an example

classD:deffunc (self):Print('D')classC (D):deffunc (self):Print('C')classB (D):deffunc (self):Print('b')classA (B, C):deffunc (self):Print('a') A=A () a.func ()#A Class A is found in category A#comment out the Func in Class AA.func ()#not in class B, first look in the left-most class B in parentheses .#comment out the Func in Class BA.func ()#C class is not, judge by C class can also find B's parent Class D, will be from Class C first Find#comment out the Func in Class CA.func ()#No in Class D, find the parent class D.

The above inheritance order can be seen:

"""     Breadth Lookup: The principle is that when not found, by the inheritance level to find out each parent class    depth lookup: The principle is an inheritance line to find the bottom to find another line " " "

And look at the nature of the Super method:

classA (object):deffunc (self):Print('A')classB (A):deffunc (self): Super (). Func ()Print('B')classC (A):deffunc (self): Super (). Func ()Print('C')classD (B, C):deffunc (self): Super (). Func ()Print('D') b=D () b.func ()#print Order is a C B D#The essence of super: not simply looking for a parent class, but based on the breadth precedence of the caller's node location

Packaging

  Encapsulation is used to protect code so that hidden properties and methods in a class are used only by providing public access, not directly.

Here is an example of a specific look:

classPerson :__keys='Quantum Coding rules'   #private static Property    def __init__(self, Name, password): Self.name=name self.__password= password#__ Property defines a private property    def __get_password(self):#__ Method defines private methods        returnSelf.__password   #can only be accessed internally    defLogin (self, name, passwd):#provide public access methods        ifName = = Self.name andpasswd = = self.__get_password():            Print('Landing Success') Person= Person ('Zzy','zzy123')#print (Person.__password) # error indicates that the person class could not find __password#print (person._person__password) # zzy123 can also view private properties on the outside through the _ Class name __ Property name, but this cannot be used! Person.login ('Zzy','zzy123')#Landing Success

Can the subclass inherit the private properties of the parent class?

class Foo:     __key = 123class  Son (foo):    print(foo.  __key)   #  Error  child class cannot inherit private properties of parent class

Polymorphic
""" Polymorphic     : Refers to a class of things in a variety of forms, Python naturally support polymorphism.    in Python, the type of duck that looks like it is used, but without any constraint, is a self-constraining behavior. such as list and tuple        advantages: Loose coupling, similar classes will not have any effect on the        shortcomings: self-restraint, arbitrary too strong "" 

Example

classHoly:defCure (Self, HP): HP+ = 100return 'The amount of blood is%s'%HPclassDiscipline:defCure (Self, HP): HP+ = 100return 'The amount of blood is%s'%HPdefCure (obj, HP):#In a strong data type language, obj must specify a data type, which can be in a variety of forms in Python    returnobj.cure (HP)#the discipline and holy classes here are similar and can be used when the same thingHoly =Holy () discipline=discipline ()Print(Cure (Holy, 20))Print(Cure (Discipline, 10))

The three main features of Python object-oriented

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.