Python Object-oriented

Source: Internet
Author: User

Object-oriented is to extract the attributes that are common in one aspect and construct a class. This class is called the parent class (Super Class).

How Python constructs a class:

1 classEmployee:2     'Employee Class'3Empcount = 0;'to count the total number of employees'4     'Construction Method'5     def __init__(self,name,salary):6Self.name =name7Self.salary =Salary8Employee.empcount + = 19 Ten     'get how many employees are currently' One     defDisplaycount (self): A         Print(U'There are currently%d employees'%employee.empcount) -  -     'Show employees ' information' the     defDisplayemployee (self): -         Print(U'Name:', Self.name,u'Salary:', self.salary)
View Code

Syntax class Name: (class name and file name) class is constructed by the system default __init__ (self) method, which is called by the system when you create the object. You can also rewrite this method, Python has no special flags for rewriting methods. It is important to note that in all methods in a class, you must write more than one self parameter in the first position. This self refers to the current instantiation of the object itself.

Classes can have private, protected, exposed properties and methods. Specific as follows:

There is also a __system__ that represents the system's

You need to be aware of the first positional argument self when building a method of a class (of course, the parameter name can be arbitrarily taken, but Self is a guild, easy code readability) must have.

Python built-in class properties:

    • __DICT__: Properties of the Class (contains a dictionary, consisting of the data properties of the Class)
    • __DOC__: Document string for Class
    • __NAME__: Class name
    • __MODULE__: The module where the class definition resides (the full name of the class is ' __main__.classname ', if the class is in an import module mymod, then classname.__module__ equals Mymod)
    • __BASES__: All parent classes of a class make up elements (containing a tuple of all the parent classes)

Call the following

1 #!/usr/bin/python2 #-*-coding:utf-8-*-3 4 classEmployee:5    'base class for all employees'6Empcount =07 8    def __init__(self, Name, salary):9Self.name =nameTenSelf.salary =Salary OneEmployee.empcount + = 1 A     -    defDisplaycount (self): -      Print "Total Employee%d"%Employee.empcount the  -    defDisplayemployee (self): -       Print "Name:", Self.name,", Salary:", Self.salary -  + Print "employee.__doc__:", Employee.__doc__ - Print "employee.__name__:", Employee.__name__ + Print "employee.__module__:", Employee.__module__ A Print "employee.__bases__:", Employee.__bases__ at Print "employee.__dict__:", Employee.__dict__
View Code

Python garbage Collection:

Like the Java language, Python uses a simple technique of reference counting to track objects in memory.

Inside Python is a record of how many references each object in use has.

An internal tracking variable, called a reference counter.

When the object is created, a reference count is created, and when the object is no longer needed, that is, the reference count of the object becomes 0 o'clock, and it is garbage collected. However, recycling is not "immediate", and the interpreter uses the garbage object to reclaim the memory space at the appropriate time.

The garbage collection mechanism not only targets objects with a reference count of 0, but can also handle circular references. Circular references refer to two of objects referencing each other, but no other variables refer to them. In this case, using only the reference count is not enough. The Python garbage collector is actually a reference counter and a cyclic garbage collector. As a supplement to the reference count, the garbage collector also pays attention to objects that are allocated a large amount (and those that are not destroyed by reference counting). In this case, the interpreter pauses to attempt to clean up all unreferenced loops.

Garbage collection involves a destructor __del__,_del__ called when the object is destroyed, and when the object is no longer being used, the __del__ method is run:

1 #!/usr/bin/python2 #-*-coding:utf-8-*-3 4 classPoint :5    def __init__(Self, x=0, y=0):6self.x =x7SELF.Y =y8    def __del__(self):9Class_name = self.__class__.__name__Ten       PrintClass_name,"destroyed" One  APT1 =Point () -Pt2 =pt1 -PT3 =pt1 the PrintID (PT1), id (PT2), ID (PT3)#the ID of the print object - delpt1 - delpt2 - delPt3
View Code

==========================================================================

Inheritance of the class:

Python supports multiple inheritance.

Syntax: Class name (base class 1 [, base class 2][, base class 3] ... ).

When you create a subclass instance object, the system does not self-invoke the constructor method in the parent class. You need to manually add a constructor method for the parent class in the child class. Such as:

1 #!/user/bin/python2 #-*-coding:utf-8-*-3 " "Parent Class" "4 classSupclass:5     'Parent Class'6supattribution = 100;7     def __init__(self):8         Print('calling the Parent class construction method');9 Ten     defParentmethod (self): One         Print('calling the Parentmethod method in the parent class'); A  -     defsetAttr (self): -Supclass.supattribution =self.supattribution; the  -     defgetAttr (self): -         Print('properties in the parent class', supclass.supattribution);
View Code
1 #!/user/bin/python2 #-*-coding:utf-8-*-3  fromSupclassImport*4 classSubclass (Supclass):5     'sub-class'6     def __init__(self):7Supclass.__init__(self);8         Print('calling subclass construction methods');9 Ten     defChildmethod (self): One         Print('calling the Childmethod method in a subclass');
View Code

You can use the Issubclass () or Isinstance () method to detect.

    • Issubclass ()-Boolean function to determine whether a class is a subclass of another class or descendant class, syntax: Issubclass (SUB,SUP)
    • Isinstance (obj, Class) Boolean function returns True if OBJ is an instance object of class or is an instance object of class subclass.

Also note the difference between the two ways that are imported in Python:

From ... import ... With import ...

The only difference between the two is:

The first type of import, when invoking a property method inside a class, is the direct class name. Method name;

The second type of import, when calling a property method inside a class, requires a fully qualified name to be called.

============================================================================

Method overrides in subclasses

The override of a method in a Python class has no special flags, you just have to do it in the subclass with the method name in the parent class. When Python calls a method, it first goes to itself to find out if it has the method, and some calls its own method. If not, look for it in the parent class, and look up at the first level. If not in the parent class, a property error is reported:

' Subclass ' ' LSS '

=====================================================================

Base Overloaded methods:

Here are some common features that you can override in your own class:

__init__ (Self[,args ...]) constructor

__del__ (self) destructor, deleting an object

__repr__ (self) converted to a form to be read by the interpreter

__STR__ (self) Format output method

__cmp__ (self,x) object comparison

======================================================================

Python supports operator overloading

1 #!/usr/bin/python2 3 classVector:4    def __init__(self, A, b):5SELF.A =a6SELF.B =b7 8    def __str__(self):9       return 'Vector (%d,%d)'%(SELF.A, self.b)Ten     One    def __add__(self,other): A       returnVector (SELF.A + other.a, self.b +other.b) -  -V1 = Vector (2,10) theV2 = Vector (5,-2) - PrintV1 + v2
View Code

Finally, the private property of the class in Python is not private in absolute sense, and the value of the private property of the class can also be changed externally.

1 #!/user/bin/python2 #-*-coding:utf-8-*-3 classclassattr:4     __secrecount= 0;#enclosing properties of a class5Publiccount = 0;#exposing properties of a class6 7     defcount (self):8Self.__secrecount+ = 1;9Self.publiccount + = 1;Ten         Print(self.)__secrecount);
View Code

Private property __secrecount can be modified by such access

The private property in the class has been modified

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.