Getting Started with Python object-oriented OOP

Source: Internet
Author: User
Tags class definition

Introduction of Object-oriented

Object-oriented programming is not unique to Python, and is supported by almost all high-level languages; object-oriented There are three main features in that language: encapsulation, inheritance, polymorphism; In this paper, we mainly talk about the concrete realization of Python object-oriented class and three major features.



Second, the object-oriented Python class characteristics one: encapsulation

Python implements object-oriented programming through classes, and programming is broadly divided into procedural-oriented functional programming and object-oriented programming.

Classes (Class) and instances (Instance) are the most important concepts for object-oriented.

1. Simple definition and use of class

Class ' name ': statement block

Such as:

Class Foo:def Bar (self): print ("foo.bar") obj = Foo () #obj即是Foo类的实例obj. Bar () #通过实例去调用调用Foo Methods in a class

Result output Foo.bar

The above is the simplest class definition and use;

2. What is self?

We note that in the above example, in addition to the class keyword used to define classes, the Def definition method (a function in a class that we call a method, which can be understood as a function encapsulated in a class is a method) has a self argument behind it, so what is the self parameter? Let's start with an example:

Class Foo:def Bar (Self,arg): Print (self,arg) z1 = Foo () print (z1) Z1.bar (11)

Output Result:

650) this.width=650; "title=" Selection _035.png "alt=" 9aa71c6f354aba5244e37212544fbef4.png-wh_ "src=" https://s2.51cto.com/ Oss/201711/17/9aa71c6f354aba5244e37212544fbef4.png-wh_500x0-wm_3-wmp_4-s_1708013327.png "/>

The above results can be seen Z1 is the Foo instance print out the memory address and the memory address of self, this means the instance itself refers to the example itself;

so self is a class instantiation object (instance), in layman's words, is that instance object invocation, refers to that instance object .


3. Instance out of object

The instance object is instantiated from the class with the OBJ = Class name ([Parameters ...]), with its own scope namespace, which has its own memory address space, as well as the ability to add an assignment to the instance object, to hold the instance's own data, and to invoke the encapsulated method or data in the class;

Class Foo:def Bar (Self,arg): print (self.name,self.age,arg) obj = Foo () #实例化obj对象obj. Name = "San" #向实例中添加对 Like name and assign value Obj.age = #向实例中添加对象age并赋值obj. Bar (666) #调用类方法并传入参数6666

Output Result:

(' San ', ' 18 ', 666)

From the example above, you can see that the class was not created with name and age when it was defined, and the obj instance object was created by assigning a value

Let obj have name and age, so instance obj can get the name in its own namespace when invoking the bar method in the class

and the age value; You can add as many values as you save to the object if there are no restrictions (__slots__) for the object to be instantiated.


4. Add assignment by __slots__ limit Aunt Instance object

From the above example, we learned that after instantiating an object from a class, you can add any number of values to the object, as long as the memory is large enough, but any uncontrolled increase may lead to potential pitfalls, so we restrict the assignment of instance objects by __slots__ function;

Class Foo: __slots__ = ("name", "Age") #只允许往实例赋name, Age def Bar (Self,arg): Print (Self.name,self.age,arg)         def other (self): print (self.other) z = Foo () #实例化zz. Name = "San" #向z对象赋值namez. Age = 18 #向z对象赋值agez. Bar ("6666") Z.other = "Othter" #向z对象赋值otherz. Other ()

Run results

650) this.width=650; "title=" Selection _036.png "alt=" Ea9e37732cb6c62cc58c1570d1a24778.png-wh_ "src=" https://s5.51cto.com/ Oss/201711/17/ea9e37732cb6c62cc58c1570d1a24778.png-wh_500x0-wm_3-wmp_4-s_66699157.png "/>

This time the assignment was not successful and was limited by the hint: "Attributeerror: ' Foo ' object has no attribute ' other '; That's what we want."


5. __init__ of constructor function

For the above example, we can assign values to the instantiated object and also limit the values that can be assigned, if you want to instantiate more than one class object, each class object has a common property value, such as name,age,sex, so we can be implemented by the constructor __init__ method, That is, when instantiating the creation of an object, pass in Name,age to achieve a similar effect as Obj.name = "san" obj.age = 18:

Class Foo:def __init__ (self,name,age): #构造方法, here are a few parameters, to instantiate the object will pass the corresponding parameter Self.name = name Self.age = Age   Print ("__init__ is start.") #对象实例化时自动执行 def foo (self,arg): print (self.name,self.age,arg) obj = foo ("San") Obj.bar ("good")

Run results

650) this.width=650; "title=" Selection _037.png "alt=" 18c3e5747dc3d500e64c039d5759db01.png-wh_ "src=" https://s2.51cto.com/ Oss/201711/17/18c3e5747dc3d500e64c039d5759db01.png-wh_500x0-wm_3-wmp_4-s_3206754160.png "/>

It can be seen from the running results that the contents of the __init__ method are executed whenever the object obj = Foo ([parameter ...]) is instantiated, and this function is used to automatically assign values to each instance when it is passed into the name,age parameter; This is the function of the construction method; The parameters are optional and whether or not you need to design the class.


Third, class Characteristics II: Inheritance

Inheritance is one of the object-oriented attributes, that is, subclasses (also called derived classes) inherit the attributes (properties, methods, etc.) of the parent class (also called the base class or superclass), and the subclass can override the methods or properties in the parent class. Speaking of inheritance at this point, python2.x and python3.x inheritance a little difference, python2.x is a classic class, through class name (object) into a new class, python3.x default is a new class; The difference between a new class and a classic class is that when multiple inheritance occurs, The inheritance order is not the same; the classic class is searched by "depth first", while the new class is breadth-first to find; Here's an example in Python 2.7 so you'll see that after the class name there is a object,python3.x that can be used without object. About depth first and breadth first not detailed here, here is an example:


1. Simple inheritance

Example:

Class F (object): #父类F def F1 (self): print ("F.f1") def F2 (self): print ("F.f2"     ) class S (F): #子类S def s1 (self): print ("s.s1") son = S () #从S类实例化对象sonson. S1 () #调用S类的s1方法son. F1 () #由于在S类中没有找到f2, so find F1 in the parent class F

Run results

650) this.width=650; "title=" Selection _039.png "alt=" 2fba26d013759d6e4fbd3ae2b784f7e0.png-wh_ "src=" https://s1.51cto.com/ Oss/201711/17/2fba26d013759d6e4fbd3ae2b784f7e0.png-wh_500x0-wm_3-wmp_4-s_168259661.png "/>

Note: Although there is no F2 method in the S class, because the S class inherits the Class F, and the F class has a F1 method, the F1 method in F can be called.


2. Rewrite

Sometimes when we inherit the parent class, the methods in the parent class may not satisfy the requirements, the methods in the parent class can be modified directly, the original class is destroyed, and other references may be affected, and the purpose of overriding the parent class method can be achieved by defining a method with the same name in the child class.

Example:

Class F (object): Def F1 (self): print ("F.f1") def F2 (self): print ("F.f2") class S (F): def-S1 (self):   Print ("S.s1") def F2 (self): # does not inherit, rewrite print ("S.f2") son = S () son.s1 () #S类的s1方法son. F1 () #继承F类的f1方法son. F2 () #S自己的f2方法, overriding (overriding) the F2 method of Class F

Operation Result:

650) this.width=650; "title=" Selection _040.png "alt=" B1fafa511759fe0979af523debe8eb62.png-wh_ "src=" https://s5.51cto.com/ Oss/201711/17/b1fafa511759fe0979af523debe8eb62.png-wh_500x0-wm_3-wmp_4-s_3755666789.png "/>

3. Calling superclass methods in subclasses

Although the above example overrides the same name method in the parent class, it satisfies the requirement, but can we refer to the methods in the superclass on the basis of overriding? You run the same name method in the superclass first, and then define your own method with the same name? The answer must be YES!

Here are two ways to enumerate together, in reality only one of them, recommended to use super:

class f (object):     def f1 (self):         print ("F.f1")     def f2 (self):         print ("F.f2") Class s (F):     def s1 (self):         print ("S.s1")     def f2 (self):   #  do not inherit, rewrite         print ("S.f2")          super (s,self). F2 ()      #调用父类f2方法一:  super (Subclass, Self). Methods in the parent class (...)         f.f2 (self)               #调用父类f2方法二: Parent class. Method (Self,....)         son = s () son.s1 ()    #S类的s1方法son. F1 ()     #继承F类的f1方法son. F2 ()    #S自己的f2方法, overriding (overriding) class F F2 method 

Operation Result:

650) this.width=650; "title=" Selection _041.png "alt=" 51e043336dc34b0227b62683247ab525.png-wh_ "src=" https://s3.51cto.com/ Oss/201711/17/51e043336dc34b0227b62683247ab525.png-wh_500x0-wm_3-wmp_4-s_4272873041.png "/>

Because the F2 method in the S class is not only output its own function S.f2 but also through two calls to the parent class F F2 method, so output two times f.f2;

Note that in order to demonstrate that only the F2 method in the parent class is called, the F2 method in the parent class is reached for inheritance and rewriting, and the other party methods in the parent class can be called by one of the two methods ;


4, class multiple inheritance

Classes can inherit multiple classes, that is, in the class class name (parent Class 1, parent Class 2,... So the question is, if the inherited class has a method with the same name, how do you choose it when called? The above mentioned that the classical class is the depth first, the new type time breadth First, this article does not do depth first and breadth first to look for the comparison, only the new type class breadth first; interested can find the information on their own.

Example:

Class Base (object): Def A (self): print ("Base.a") class F1 (Base): Def A1 (self): print (' f1.a ') def A11 (self): print ("F1.a11") class F2 (Base): Def A2 (self): print (' f2.a ') def A11 (self): print ("F2.a11") class S (F1,F2): Passclass S2 (f2,f1): Passobj = S () obj.a11 () Obj2 = S2 () obj2.a11 ()

Operation Result:

650) this.width=650; "title=" Selection _042.png "alt=" D6e7b907756a11b080b43873044109ff.png-wh_ "src=" https://s5.51cto.com/ Oss/201711/17/d6e7b907756a11b080b43873044109ff.png-wh_500x0-wm_3-wmp_4-s_2176283826.png "/>

The obj inheritance order is f1,f2 result is f1.a11

OBJ2 inheritance order is f2,f1 result is F2.all


5. Multiple inheritance lookup with intersection


The Obj object is instantiated from Class A, Class A inherits the B and C classes, Class B inherits the D,c class, and the Baba method has the class C and Class D, so what happens to the Obj.baba () method?

Example:

Class D:def Bar (self): print (' D.bar ') def Baba (self): print ("D.baba") class C (D): Def bar (self):  Print (' C.bar ') def Baba (self): print ("C.baba") class B (D): Def bar (self): print (' B.bar ') class A (B, C): Def bar (self): print (' A.bar ') obj = A () Obj.bar () Obj.baba ()

Operation Result:

650) this.width=650; "title=" Selection _045.png "alt=" 240e625fda7accf24feb8d18c15590c5.png-wh_ "src=" https://s1.51cto.com/ Oss/201711/17/240e625fda7accf24feb8d18c15590c5.png-wh_500x0-wm_3-wmp_4-s_993808898.png "/>


# when executing the bar and Baba methods
# First go to a class to find, if not in Class A, then continue to the Class B, if there is a class B, then continue to the Class C, if there is a Class C, then continue to find in Class D, if still not found, the error
# So, look in order: A--B--and C--D
# in the process of finding the bar method above, once found, the search process is immediately interrupted and no further search


The same example we recall python2.7 as the classic class execution, see the results.

650) this.width=650; "title=" Selection _046.png "alt=" 2a17181b8338f0c29f30416761f2e9df.png-wh_ "src=" https://s4.51cto.com/ Oss/201711/17/2a17181b8338f0c29f30416761f2e9df.png-wh_500x0-wm_3-wmp_4-s_2383644878.png "/>

When executing the bar and Baba methods
First go to a class to find, if not in Class A, then continue to find in class B, if there is a class B, then continue to find in Class D, if there is a class D, then continue to the C class to find, if still not found, the error
So, look in order: A-and B--and D-and C
In the process of finding the bar method above, once found, the search process is immediately interrupted and no further search

The Baba method here is found in D, so it appears as D.baba

Depth-first and breadth-first lookup order

650) this.width=650; "title=" Qq20171117152450.png "alt=" 67efcf62e4f16c675b9552340a4f0194.png-wh_ "src=" https:// S5.51cto.com/oss/201711/17/67efcf62e4f16c675b9552340a4f0194.png-wh_500x0-wm_3-wmp_4-s_4162088720.png "/>


6. __init__ execution sequence of multiple inheritance

The following is a simulation of the practice of multiple inheritance in the case of the implementation of the __init__ construction method, to help us read the project source code.

Example:

class baserequest:    # (3)    def __init__ (self):        print ("Baserequest.init") Class requesthandler (BaseRequest):   # (2)     def __init__ (self):         print (" Requesthandler.init ")         baserequest.__init__ (self)      #调用父类的__init__方法     #     super (requesthandler,self). __init __ ()     def serve_forever (self):      # (5)          print ("Requesthandler.serve_forever")          self.process_request ()     def process_request (self):         print (' requesthandler.process_request ') class minx:    def  process_request (self):   # (6)         print ("Minx.process_request") Class son ( Minx,requesthandler):     passobj = son ()      # (1) Obj.serve_forever ()     # (4)

The number after the comment above is the process of execution. The role of obj = Son ():

Instantiate the Obj object;

Execute the __init__ construction method, in the multi-inheritance environment, and the above call other classes to find the same, first find __init__ in son class if not in the order of the new class to find the __init__ of the inherited class, here first find Minx, no, Then find the RequestHandler class, perform the printing "Requesthandler.init", the __init__ in the parent class to execute the __init__ method again, so print out "baserequest.init";

Execute Obj.serve_forever (), the same search, print out "Requesthandler.serve_forever", notice here again called the Self.process_request () method, Since self refers to the object that is being called obj, the Obj.process_request () method, it is re-searched sequentially from son (Minx,requesthandler) instead of Process_ under the RequestHandler class. Reques method. So find the Process_request method under Minx and get the result: "Minx.process_request"


The results of the implementation are as follows:

650) this.width=650; "title=" Selection _047.png "alt=" 43461690e1de0c056789b9529534ec27.png-wh_ "src=" https://s3.51cto.com/ Oss/201711/17/43461690e1de0c056789b9529534ec27.png-wh_500x0-wm_3-wmp_4-s_1302415823.png "/>



Iv. python-oriented polymorphism of the image

A polymorphic simple understanding is that the same method shows a different effect when it is called by an object, such as the addition of a mathematical operation when the number is added, and a connector when the string is added;

Python's object-oriented native support polymorphism, unlike strongly typed languages like Java, must specify a type when passing parameters, and Python does not have this limitation, which is one of the reasons why Python natively supports polymorphism.



This paper mainly describes the three main characteristics of Python object-oriented, encapsulation, inheritance and polymorphism, inheritance has multiple inheritance, new inheritance and classical class inheritance difference. Personal summary, if there is improper welcome to correct.



This article is from the "Learning, learning" blog, please be sure to keep this source http://dyc2005.blog.51cto.com/270872/1982808

Getting Started with Python object-oriented OOP

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.