Python object-oriented

Source: Internet
Author: User

Python object-oriented
Introduction to object-oriented technology

  • Class: a set of objects with the same attributes and methods. It defines the attributes and Methods shared by each object in the set. The object is a class instance.
  • Class variables: class variables are public in the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are generally not used as instance variables.
  • Data Member: class variables or instance variables are used to process data related to the class and its instance objects.
  • Method Rewriting: if the method inherited from the parent class cannot meet the requirements of the subclass, you can rewrite it. This process is called override, or method rewriting.
  • Instance variable: a variable defined in the method. It only applies to the class of the current instance.
  • Inheritance: A derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where a Dog-type object is derived from the Animal class, which simulates the relationship "is a (is-a)" (example diagram, Dog is an Animal ).
  • Instantiation: creates an instance of a class and a specific object of the class.
  • Method: The function defined in the class.
  • Object: a data structure instance defined by a class. The object includes two data members (class variables and instance variables) and methods. Create class

    Use the class statement to create a new class. The class is followed by the class name and ends with a colon, as shown in the following example:

    Class ClassName: 'class help information' # class document string class_suite # class body

    Class help information can be viewed through ClassName. _ doc.

    Class_suite consists of class members, methods, and data attributes.

    Instance

    The following is a simple Python class instance:

    #! /Usr/bin/python #-*-coding: UTF-8-*-class Employee: 'All employees' base classes 'empcount = 0 def _ init _ (self, name, salary): self. name = name self. salary = salary Employee. empCount + = 1 def displayCount (self): print "Total Employee % d" % Employee. empCount def displayEmployee (self): print "Name:", self. name, ", Salary:", self. salary
    • The empCount variable is a class variable whose values are shared among all instances of the class. You can use Employee. empCount to access the internal or external classes.
    • The first method _ init _ () is a special method called a class constructor or initialization method, this method is called when an instance of this class is created. Create an Instance Object

      To create an instance of a class, you can use the class name and use the _ init _ method to accept parameters.

      "Create the first object of the Employee class" emp1 = Employee ("Zara", 2000) "create the second object of the Employee class" emp2 = Employee ("Manni", 5000)
      Access attributes

      You can use vertex (.) to access the attributes of an object. Use the following Class Name:

      emp1.displayEmployee()emp2.displayEmployee()print "Total Employee %d" % Employee.empCount

      Complete instance:

      #! /Usr/bin/python #-*-coding: UTF-8-*-class Employee: 'All employees' base classes 'empcount = 0 def _ init _ (self, name, salary): self. name = name self. salary = salary Employee. empCount + = 1 def displayCount (self): print "Total Employee % d" % Employee. empCount def displayEmployee (self): print "Name:", self. name, ", Salary:", self. salary "create the first object of the Employee class" emp1 = Employee ("Zara", 2000) "create the second object of the Employee class" emp2 = Employee ("Manni", 5000) emp1.displayEmployee () emp2.displayEmployee () print "Total Employee % d" % Employee. empCount

      The output result is as follows:

      Name :  Zara ,Salary:  2000Name :  Manni ,Salary:  5000Total Employee 2

      You can add, delete, and modify the attributes of a class as follows:

      Emp1.age = 7 # Add an 'age' attribute emp1.age = 8 # modify the 'age' attribute del emp1.age # Delete the 'age' attribute

      You can also use the following functions to access attributes:

      • Getattr (obj, name [, default]): the attribute of the access object.
      • Hasattr (obj, name): Check whether an attribute exists.
      • Setattr (obj, name, value): sets an attribute. If the property does not exist, a new property is created.
      • Delattr (obj, name): deletes an attribute.
        Hasattr (emp1, 'age') # returns True if the 'age' property exists. Getattr (emp1, 'age') # Return the value of the 'age' attribute setattr (emp1, 'age', 8) # Add the attribute 'age' with the value of 8 delattr (empl, 'age') # Delete the attribute 'age'
        Python built-in class attributes
        • _ Dict _: class attributes (including a dictionary consisting of class data attributes)
        • _ Doc _: Document string of the class
        • _ Name __: Class name
        • _ Module __: module where the class definition is located (the full name of the class is '_ main __. classname'. If the class is located in mymod of an import module, then className. _ module _ equals to mymod)
        • _ Bases _: Elements of all parent classes of the class (including tuples consisting of all parent classes)

          The Python built-in class property call example is as follows:

          #! /Usr/bin/python #-*-coding: UTF-8-*-class Employee: 'All employees' base classes 'empcount = 0 def _ init _ (self, name, salary): self. name = name self. salary = salary Employee. empCount + = 1 def displayCount (self): print "Total Employee % d" % Employee. empCount def displayEmployee (self): print "Name:", self. name, ", Salary:", self. salaryprint "Employee. _ doc __: ", Employee. _ doc _ print "Employee. _ name __: ", Employee. _ name _ print "Employee. _ module __: ", Employee. _ module _ print "Employee. _ bases __: ", Employee. _ bases _ print "Employee. _ dict __: ", Employee. _ dict __

          The output result is as follows:

          Employee. _ doc __: the base class of all employees. _ name __: EmployeeEmployee. _ module __: _ main _ Employee. _ bases __: () Employee. _ dict __:{ '_ module _': '_ main _', 'displaycount ':
                   
                    
          , 'Empcount': 0, 'displayemployee ':
                    
                     
          , '_ Doc __': '\ xe6 \ x89 \ x80 \ xe6 \ x9c \ x89 \ xe5 \ x91 \ x98 \ xe5 \ xb7 \ xa5 \ xe7 \ x9a \ x84 \ xe5 \ x9f \ xba \ xe7 \ xb1 \ xbb ', '_ init __':
                     
                      
          }
                     
                    
                   
          Python object destruction (garbage collection)

          Like the Java language, Python uses the reference count simple technology to track objects in memory.

          In Python, the number of references of all objects in use is recorded.

           

          An internal trace variable is called a reference counter.

          When an object is created, a reference count is created. When this object is no longer needed, that is, when the reference count of this object is changed to 0, it is recycled. However, the recycle object is not "immediate". At the right time, the interpreter recycles the memory space occupied by the spam object.

          A = 40 # create an object <40> B = a # Add reference, <40> Count c = [B] # Add reference. <40> count del a # reduce reference <40> Count B = 100 # reduce reference <40> Count c [0] =-1 # reduce reference <40> count

          The garbage collection mechanism is applicable not only to objects with 0 reference counts, but also to circular references. Loop Reference refers to the mutual reference between two objects, but no other variables reference them. In this case, it is not enough to use only the reference count. The Python garbage collector is actually a reference counter and a circular garbage collector. As a supplement to reference counting, the garbage collector will also pay attention to objects with a large total allocation volume (and those that are not destroyed by reference counting. In this case, the interpreter pauses and tries to clear all the loops that are not referenced.

          Instance

          The Destructor _ del _ ,__ del _ is called when the object is destroyed. When the object is no longer used, run the __del _ method:

          #! /Usr/bin/python #-*-coding: UTF-8-*-class Point: def _ init _ (self, x = 0, y = 0): self. x = x self. y = y def _ del _ (self): class_name = self. _ class __. _ name _ print class_name, "Destroy" pt1 = Point () pt2 = pt1pt3 = pt1print id (pt1), id (pt2), id (pt3) # print the iddel pt1del pt2del pt3 of the object

          The running result of the above instance is as follows:

          3083401324 3083401324 3083401324 Point destruction

          Note: You usually need to define a class in a separate file,

          Class inheritance

          One of the main benefits of object-oriented programming is code reuse. One of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be fully understood as the relationship between types and subtypes between classes.

          Note: inherited syntax class derived class name (base class name )://... in the base class name writing brackets, the basic class is specified in the tuples when the class is defined.

          Some features of inheritance in python:

          • 1: The Construction (_ init _ () method) of the base class in the inheritance class will not be automatically called. It needs to be called in the construction of its derived class.
          • 2: when calling a base class method, you must add the base class name prefix and the self parameter variable. Unlike calling a common function in a class, the self parameter is not required.
          • 3: Python always first looks for the corresponding type of method. If it cannot find the corresponding method in the derived class, it starts to look for it one by one in the base class. (Search for the called method in this class before finding it in the base class ).

            If more than one class is listed in the inheritance tuples, it is called "Multi-inheritance ".

            Syntax:

            The declaration of a derived class is similar to that of its parent class. The list of inherited base classes follows the class name, as shown below:

            class SubClassName (ParentClass1[, ParentClass2, ...]):   'Optional class documentation string'   class_suite

            Instance:

            #! /Usr/bin/python #-*-coding: UTF-8-*-class Parent: # define Parent class parentAttr = 100 def _ init _ (self ): print "calling the Parent class constructor" def parentMethod (self): print 'Call the Parent class method' def setAttr (self, attr): Parent. parentAttr = attr def getAttr (self): print "Parent class property:", Parent. parentAttrclass Child (Parent): # define the subclass def _ init _ (self): print "Call the subclass constructor" def childMethod (self ): print 'call subclass method child method' c = Child () # instantiate subclass c. childMethod () # Call The subclass method c. parentMethod () # Call the parent class method c. setAttr (200) # Call the method c of the parent class again. getAttr () # Call the method of the parent class again

            The code execution result is as follows:

            Call subclass constructor call subclass method child method call parent class method parent class property: 200

            You can inherit multiple classes

            Class A: # define class ..... class B: # define class B ..... class C (A, B): # inherit classes A and B .....

            You can use the issubclass () or isinstance () method for detection.

            • Issubclass ()-Boolean function determines whether a class is a subclass or descendant class of another class. Syntax: issubclass (sub, sup)
            • The Boolean function of isinstance (obj, Class) returns true if obj is an instance object of the Class or an instance object of a Class subclass. Method Rewriting

              If the function of your parent class method cannot meet your needs, you can rewrite the method of your parent class in the subclass:

              Instance:

              #! /Usr/bin/python #-*-coding: UTF-8-*-class Parent: # define Parent class def myMethod (self ): print 'call Parent class method' class Child (Parent): # define subclass def myMethod (self): print' call subclass method' c = Child () # subclass instance c. myMethod () # subclass calls override method

              The output result is as follows:

              Call subclass Method
              Basic overload method

              The following table lists some common functions that can be rewritten in your own class:

              Serial number Method, description & simple call
              1 _ Init _ (self [, args...])
              Constructor
              Simple call method:Obj = className (args)
              2 _ Del _ (self)
              Structure Method to delete an object
              Simple call method:Dell obj
              3 _ Repr _ (self)
              Converted to the form for the interpreter to read
              Simple call method:Repr (obj)
              4 _ Str _ (self)
              Used to convert a value into a form suitable for reading.
              Simple call method:Str (obj)
              5 _ Cmp _ (self, x)
              Object comparison
              Simple call method:Cmp (obj, x)
              Operator overload

              Python also supports Operator overloading. The example is as follows:

              #!/usr/bin/pythonclass Vector:   def __init__(self, a, b):      self.a = a      self.b = b   def __str__(self):      return 'Vector (%d, %d)' % (self.a, self.b)      def __add__(self,other):      return Vector(self.a + other.a, self.b + other.b)v1 = Vector(2,10)v2 = Vector(5,-2)print v1 + v2

              The code execution result is as follows:

              Vector(7,8)
              Private attributes of class attributes and method classes

              _ Private_attrs: It starts with two underscores and declares that this attribute is private and cannot be used outside the class or accessed directly. Self. _ private_attrs is used in internal methods of the class.

              Class Method

              Inside the class, you can use the def keyword to define a method for the class. Unlike the general function definition, the class method must contain the self parameter and be the first parameter.

              Class private Method

              _ Private_method: it must start with an underscore. It is declared as a private method and cannot be called outside the class. Call self. _ private_methods inside the class

              Instance
              #! /Usr/bin/python #-*-coding: UTF-8-*-class JustCounter :__ secretCount = 0 # private variable publicCount = 0 # public variable def count (self): self. _ secretCount + = 1self. publicCount + = 1 print self. _ secretCountcounter = JustCounter () counter. count () counter. count () print counter. publicCountprint counter. _ secretCount # error: the instance cannot access private variables

              Python changes the name to include the Class Name:

              122 Traceback (most recent call last): File "test. py", line 17, in
                           
                            
              Print counter. _ secretCount # error. The instance cannot access the private variable AttributeError: JustCounter instance has no attribute '_ secretCount'
                           

              Python does not allow instantiated classes to access private data, but you can use object. _ className _ attrName to access the attribute and replace the following code with the last line of code of the above Code:

              .........................print counter._JustCounter__secretCount

              Run the preceding code and the execution result is as follows:

              1222

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.