Object-oriented python: object-oriented python

Source: Internet
Author: User

Object-oriented python: object-oriented python

I. Classes and objects

1. What is a class?
Class.
Object refers to an instance of a specific abstract class.

Does the above statement seem a bit cloudified. Yes, professional explanations are hard to understand. This is an expert. In fact, for a simple example, you can understand it.
For example, it is called an animal. The animal is the so-called class above, and the ox, horse, chicken, duck, and goose are the corresponding instance in the class, that is, the object. Ox is an object, goat is an object ,... Now I understand.

How to define and use python classes.

 

2. Class Members: we can see that the class contains many members. What is the classification of the members in the class?

3. Three main features of classes: encapsulation, inheritance, and polymorphism (python polymorphism is rarely used)

Encapsulation: Let's look at a small problem. For example, to add, delete, modify, and query a database, we can define four functions to implement these functions. However, each time we call these functions, we must pass parameters to these functions and inform them of the database instances, user names, passwords, port numbers, and other information to be side by side. In this case, each call transmits the same information. 1. Is there a better way to use this repeated operation? 2. For function-oriented calls, we do not know who uses the function.

For object-oriented users, the concept of encapsulation is actually used to solve the problems arising from such scenarios. In fact, we can put the common information in the parameters in the constructor, that is, when an object is instantiated, this information is assigned to this object, then, you do not need to repeatedly input these parameters in the function when calling the method. When calling a method with a specified object to call these methods, you will know who called them. For example, you will be clear.

1 >>># function implementation 2... 3 >>> def fetch (conn_info): 4... print "use % s conn to db for fetch" % conn_info 5... 6 >>> def modify (conn_info): 7... print "use % s conn to db for modify" % conn_info 8... 9 >>># function call. Each call requires the input of parameter 10... fetch ('Scott 123 127.0.0.1 ') 11 use scott 123 127.0.0.1 conn to db for fetch12 >>> modify ('Scott 123 127.0.0.1 ') 13 use scott 123 127.0.0.1 conn to db for modify14 >>>> 15 >>## class implementation 16... class A: 17... def _ init _ (self, conn_info): 18... self. conn_info = conn_info19... def fetch (self): 20... print "use % s conn to db for fetch" % self. conn_info21... def modify (self): 22... print "use % s conn to db for modify" % self. conn_info23... 24 >>># class call 25... # instantiate an object and specify who (obj) calls it. The public parameters only need to be passed once during instantiation. 26... obj = A ('Scott 123 127.0.0.1 ') 27> obj. fetch () 28 use scott 123 127.0.0.1 conn to db for fetch29 >>> obj. modify () 30 use scott 123 127.0.0.1 conn to db for modify31 >>>

 

4. class inheritance

What is inheritance? For example, for two people A and B, A can walk and eat, B can also walk and eat, and B can also draw, but A does not, then we can say that B inherits from

# Inherited definition class A: def func1 (self): print "func1" class B (A): def func2 (self ): print "func2" # instantiate object obj2 = B () # Call the parent class method obj2.func1 ()

The code above indicates that Class B inherits from Class A, is it very simple, and inherits from Class A (after the parent class, you can call the method of your class through the object)

 

5. Multi-inheritance: Can a class only inherit from another class? Can it inherit from multiple classes? The answer is yes. This is special to python and is not available in other languages. The problem arises. If A Class D inherits from B and C, and B and C both inherit from Class A, Class B has no func method, and class C has A method func, class A also has A method func. Which class is called by Class D after Class D is instantiated?

Let's take an example. Before looking at the example, let's talk about the classification of classes in python (why? Because the above problems are divided into two situations, classic classes and new classes are different.) in python, classes are classified into classic classes and new classes, to define a new class, you only need to specify that the class inherits from the object class in the definition, as shown below:

# Classic class A: pass # New class B (object): pass
# Multi-inheritance class A: def func (self): print "funcA" class B (A): passclass C (A): def func (self ): print "funcC" class D (B, C): pass # instantiate object obj = D () # function call, print funcAobj. func () # New class multi-inheritance class A (object): def func (self): print "funcA" class B (A): passclass C (): def func (self): print "funcC" class D (B, C): pass # instantiate object obj = D () # new class function call, print funcCobj. func ()Sample Code for calling sequence of classic and new class methods

Execution result:

1 >>>## multi-inheritance of classic Classes 2... class A: 3... def func (self): 4... print "funcA" 5... 6 >>> class B (A): 7... pass 8... 9 >>> class C (A): 10... def func (self): 11... print "funcC" 12... 13 >>> class D (B, C): 14... pass15... 16 >>># instantiate object 17... obj = D () 18 >>> # function call, print funcA19... obj. func () 20 funcA21 >>> 22 >>## inheritance of new classes 23... class A (object): 24... def func (self): 25... print "funcA" 26... 27 >>> class B (A): 28... pass29... 30 >>> class C (A): 31... def func (self): 32... print "funcC" 33... 34 >>> class D (B, C): 35... pass36... 37 >>># instantiate object 38... obj = D () 39 >>> # new class function call, print funcC40... obj. func () 41 funcC

# From the above results, we can see that
Classic search is based on the principle of depth first. The query order is D-> B-> A. If no value is found, an error is returned.
The query sequence of the new category is D-> B-> C-> A. If no query is found, an error is returned.

 

6. Special members commonly used in the class
Class Name. _ doc _: print the annotation information of the class (it refers to the annotation information caused)
Class Name/object. _ dict __: return the member dictionary contained in the class or object
_ Call __: defines this method in the class. In fact, it is the method used to execute object () calls.
_ Str __: if the _ str _ method is defined in a class, the return value of this method is output by default when an object is printed.

7. Other problems
Isinstance (obj, cls): checks whether obj is a cls-like object.
Issubclass (sub, super): checks whether the sub class is a derived class of the super class.

8. Common operation examples of Classes

Class Person: class_v = 'betiful '# static field/class variable salary = 10000 _ private_v = 'you can \' t read me from outned' # private class variable def _ init __( self, name, age): self. name = name ## common field self. age = age _ male = 'girl '# static private field self. favorite = 'cat' def speak (self, des): # general method print "I'm {0}, age {1}, today is a {2} day !, So {3} ". format (self. name, self. age, Person. class_v, des) @ staticmethod def static_m (): # static method print" This is a static method! "@ Classmethod # class method def class_m (cls, * args, ** kwargs): print" This is a class method! "@ Property def attr_m (self): # The attribute is actually the return self. favorite # here is just an example. In actual application, the corresponding value is obtained through some logic processing. @ attr_m.setter # sets the attribute value def attr_m (self, value): self. favorite = value return self. favorite @ attr_m.deleter # Delete the attribute value def attr_m (self): del self. favorite def read_private (self): # print Person in the normal method. _ private_vclass wo (Person): # inherit def _ init _ (self, name): self. name = name def des (self): print "% s is a lovely Girl! "% Self. name # class instantiation obj = Person ('Min', 18) # print obj. salaryprint Person. salaryobj. salary + = 2000 print obj. salaryprint Person. salaryPerson. salary + = 50000 print obj. salaryprint Person. salary # From the above results, we can see that the variable value does not affect the value of the variable by modifying the class variable of the object. # the normal method calls obj. speak ('Nice ') # Call a static method. The class must call Person. static_m () # Call the class method. The class must call the Person. class_m () # access attribute obj. attr_mobj.attr_m = 'always cat! 'Print obj. attr_mdel obj. attr_m # test the print obj of the private class variable. read_private () # method for accessing the inherited Class min = wo ('Min') min. des () # Person class variable Person. class_v # access the private class variable Person. _ private_v # unable to access obj. _ Person _ private_v # force access to private membersClass common operation example code

Execution result:

1 >>> class Person: 2... class_v = 'beautiful' # static field/class variable 3... salary = 10000 4... _ private_v = you can \'t read me from outside # private class variable 5... def _ init _ (self, name, age): 6... self. name = name # common field 7... self. age = age 8... _ male = 'girl '# static private field 9... self. favorite = 'cat' 10... def speak (self, des): # general method 11... print "I'm {0}, age {1}, today is a {2} day !, So {3 }". format (self. name, self. age, Person. class_v, des) 12... @ staticmethod13... def static_m (): # static method 14... print "This is a static method! "15... @ classmethod # class method 16... def class_m (cls, * args, ** kwargs): 17... print" This is a class method! "18... @ property19... def attr_m (self): # The attribute is actually the method variant 20... return self. favorite # here is just an example. In actual application, the corresponding value 21 is usually obtained through some logic processing... @ attr_m.setter # Set the attribute value 22... def attr_m (self, value): 23... self. favorite = value24... return self. favorite25... @ attr_m.deleter # Delete attribute value 26... def attr_m (self): 27... del self. favorite28... def read_private (self): # general method 29... print Person. _ private_v30... 31 >>> class wo (Perso N): # inherit 32... def _ init _ (self, name): 33... self. name = name34... def des (self): 35... print "% s is a lovely girl! "% Self. name36... 37 >>># class instantiation 38... obj = Person ('Min', 18) 39 >>> # callback class variable 40... print obj. salary41 1000042 >>> print Person. salary43 1000044 >>> obj. salary + = 200045 >>> print obj. salary46 1200047 >>> print Person. salary48 1000049> Person. salary + = 5000050 >>> print obj. salary51 1200052 >>> print Person. salary53 6000054 >>## from the above results, we can see that the modified object class variable does not affect the variable value 55... 56 >>># call common methods 57... obj. spea K ('Nice ') 58 I'm min, age 18, today is a beautiful day !, So nice59 >>> # Call a static method. The class must call 60... Person. static_m () 61. This is a static method! 62 >>># to call a class method, you must call 63... Person. class_m () 64 This is a class method! 65 >>> # access attribute 66... obj. attr_m67 'cat' 68 >>> obj. attr_m = 'always cat! '69 >>> print obj. attr_m70 always cat! 71 >>> del obj. attr_m72 >>># test the printing of private class variables 73... obj. read_private () 74 you can't read me from outside75 >>> # method for accessing the inherited class 76... min = wo ('Min') 77 >>> min. des () 78 min is a lovely girl! 79 >>> 80 >>># class variable 81... person. class_v82 'betiful '83 >>> # access private class variable 84... person. _ private_v # unable to access 85 Traceback (most recent call last): 86 File "<stdin>", line 2, in <module> 87 AttributeError: class Person has no attribute '_ private_v' 88 >>> obj. _ Person _ private_v # force access to private members 89 "you can't read me from outside" 90 >>>

 

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.