Getting started with Python example series 21 object oriented (beginner)

Getting started with Python example series 21 object oriented (beginner)

 

Python's object-oriented syntax format is significantly different from other languages (C + +, Java, C# etc.), with similar concepts but far different syntax formats.

Create class

Use the class statement to create a new class, followed by the class name and ending with a colon:

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

The help information of the class (class document string) can be accessed through the class name__ doc__ View.

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

class ClassName:
   'Help information for class'   # Class document string
   pass    # Class body

print(ClassName.__doc__)

result

Class

 

The following is an example of a simple Python class:

class Employee:
    'Base class for all employees'
    empCount = 0  # Class variable whose value will be shared among all instances of this class. Can be used in internal or external classes Employee.empCount visit

    def __init__(self, name, salary):  # Class constructor or initialization method, which will be called when an instance of this class is created
        self.name = name  # name  Instance variable
        self.salary = salary  # salary Instance variable
        Employee.empCount += 1

    def displayCount(self):  # Example method
        print("Total Employee %d" % Employee.empCount)

    def displayEmployee(self):  # Example method
        print("Name: ", self.name, ", Salary:", self.salary)

a = Employee('Sam',123)
a.displayEmployee()
a.displayCount()

b = Employee('John',222)
b.displayEmployee()
b.displayCount()

result

Name:  Sam , Salary: 123
Total Employee 1
Name:  John , Salary: 222
Total Employee 2

  • The empCount variable is a class variable whose value will be shared among all instances of the class. Employee. Can be used in internal or external classes empCount access. (internal and external) https://www.cnblogs.com/emanlee/p/15806119.html)

  • The first method__ init__ () method is a special method called class constructor or initialization method. It will be called when an instance of this class is created.

  • self represents the instance of a class. self is necessary when defining the method of a class, although it is not necessary to pass in the corresponding parameters when calling.

self represents an instance of a class, not a class

Class methods are only different from ordinary functions -- they must have an additional first parameter name, which is conventionally called self.

class Test:
    def prt(self):
        print(self)
        print(self.__class__)
 
t = Test()
t.prt()
The execution result of the above example is:
<__main__.Test object at 0x0124FDF0>
<class '__main__.Test'>

It is obvious from the execution results that self represents the instance of the class and the address of the current object, while self__ class__ Points to the class.

self is not a python keyword. We can replace it with other characters normally:

class Test:
    def prt(xxx):
        print(xxx)
        print(xxx.__class__)
 
t = Test()
t.prt()
The execution result of the above example is:
<__main__.Test object at 0x0124FDF0>
<class '__main__.Test'>

Create instance object

In other programming languages (C + +, Java, C#), the keyword new is generally used to instantiate a class, but this keyword is not available in Python. The instantiation of a class is similar to a function call.

The following class is instantiated with the name Employee, and__ init__ Method to receive parameters.

"establish Employee Class"
emp1 = Employee("Zara", 2000)
"establish Employee Class"
emp2 = Employee("Manni", 5000)
 

Access properties

You can use point numbers To access the properties of the object. Use the following class names to access class variables:

emp1.displayEmployee()
emp2.displayEmployee()
 

Complete example:

class Employee:
   'Base class for all employees'
   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)
 
"establish Employee Class"
emp1 = Employee("Zara", 2000)
"establish Employee Class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)

Execute the above code and the output results are as follows:

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

You can add, delete and modify the properties of the class, as shown below:

emp1.age = 7  # Add a 'age' attribute
emp1.age = 8  # modify 'age' attribute
del emp1.age  # delete 'age' attribute
 

You can also access properties by using the following functions:

  • getattr(obj, name[, default]): access the attributes of the object.
  • hasattr(obj,name): check whether there is an attribute.
  • setattr(obj,name,value): set an attribute. If the property does not exist, a new property is created.
  • delattr(obj, name): deletes an attribute.
hasattr(emp1, 'age')    # If present 'age' Property return True. 
getattr(emp1, 'age')    # return 'age' The value of the property
setattr(emp1, 'age', 8) # Add attribute 'age' The value is 8
delattr(emp1, 'age')    # Delete attribute 'age'

 

Python built-in class properties

  • __ dict__ : Class properties (including a dictionary, which is composed of class data properties)
  • __ doc__ : Class
  • __ name__: Class name
  • __ module__: The module where the class definition is located (the full name of the class is' _. Classname '. If the class is in an import module mymod, then classname. _ module_ is equal to mymod)
  • __ bases__ : Class (including a tuple composed of all parent classes)

Examples of Python built-in class attribute calls are as follows:

class Employee:
    'Base class for all employees'
    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)


print("Employee.__doc__:", Employee.__doc__)

print("Employee.__name__:", Employee.__name__)

print("Employee.__module__:", Employee.__module__)

print("Employee.__bases__:", Employee.__bases__)

print("Employee.__dict__:", Employee.__dict__)

 

Execute the above code and the output results are as follows:

Employee.__doc__: Base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'__module__': '__main__', '__doc__': 'Base class for all employees', 'empCount': 0, '__init__': <function Employee.__init__ at 0x00A9AC00>, 'displayCount': <function Employee.displayCount at 0x00A9AC48>, 'displayEmployee': <function Employee.displayEmployee at 0x00A9AC90>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>}

 

 

python object destruction (garbage collection)

Python uses the simple technique of reference counting to track and recycle garbage.

Python records how many references there are for all objects in use.

An internal trace variable called a reference counter.

When an object is created, a reference count is created. When the object is no longer needed, that is, when the reference count of the object becomes 0, it is garbage collected. However, recycling is not "immediate". The interpreter will recycle the memory space occupied by garbage objects at an appropriate time.

a = 40      # create object  <40>
b = a       # Add references, <40> Count of
c = [b]     # Add reference.  <40> Count of

del a       # Reduce references <40> Count of
b = 100     # Reduce references <40> Count of
c[0] = -1   # Reduce references <40> Count of
 

The garbage collection mechanism is not only for objects with a reference count of 0, but also for circular references. Circular reference means that two objects refer to each other, but no other variables refer to them. In this case, using only reference counts is not enough. Python's garbage collector is actually a reference counter and a circular garbage collector. As a supplement to the reference count, the garbage collector also pays attention to objects with a large total amount of allocation (that is, those not destroyed by the reference count). In this case, the interpreter pauses and tries to clean up all unreferenced loops.

 

Destructor__ del__ ,__ del__ Called when the object is destroyed. When the object is no longer used__ del__ Method run:

#!/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 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3)) # Print object id
del pt1
del pt2
del pt3

The operation results of the above examples are as follows:

15777616 15777616 15777616
Point Destroy
 

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 realize this reuse is through inheritance mechanism.

A new class created by inheritance is called a subclass or derived class, and the inherited class is called a base class, a parent class, or a superclass.

Inheritance grammar

class Derived class name(Base class name)
    ...
 

Some features of inheritance in python:

  • 1. If you need the constructor of the parent class in a subclass, you need to explicitly call the constructor of the parent class or do not override the constructor of the parent class.
  • 2. When calling the method of the base class, you need to prefix the class name of the base class and take the self parameter variable. The difference is that the class does not need to bring self parameters when calling ordinary functions.
  • 3. Python always looks for the method of the corresponding type first. If it can't find the corresponding method in the derived class, it starts to look for it one by one in the base class. (first find the called method in this class, and then find it in the base class if it cannot be found).

If more than one class is listed in the inheritance tuple, it is called "multiple inheritance".

Syntax:

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

class SubClassName (ParentClass1[, ParentClass2, ...]):
    ...

 


class Parent:        # Define parent class
   parentAttr = 100
   def __init__(self):
      print( "Call the parent class constructor")
 
   def parentMethod(self):
      print('Call parent method')
 
   def setAttr(self, attr):
      Parent.parentAttr = attr
 
   def getAttr(self):
      print( "Parent class properties :", Parent.parentAttr)
 
class Child(Parent): # Define subclasses
   def __init__(self):
      print( "Call subclass constructor")
 
   def childMethod(self):
      print( 'Call subclass method')
 
c = Child()          # Instantiate subclasses
c.childMethod()      # Call methods of subclasses
c.parentMethod()     # Call parent method
c.setAttr(200)       # Call the method of the parent class again - Set attribute value
c.getAttr()          # Call the method of the parent class again - Get property value

The execution results of the above code are as follows:

Call subclass constructor
 Call subclass method
 Call parent method
 Parent attribute: 200

You can inherit multiple classes

Class A: # define class A
.....

Class B: # define class B
.....

class C(A, B): # inherits classes A and B
.....

You can use the issubclass() or isinstance() methods to detect.

  • issubclass() - Boolean function to judge whether a class is a subclass or descendant of another class. Syntax: issubclass(sub,sup)
  • isinstance(obj, Class) Boolean function returns true if obj is an instance object of Class or an instance object of a subclass of Class.

Method rewrite

If the function of the parent method cannot meet the requirements, you can override the parent method in the subclass:

example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Parent:        # Define parent class
   def myMethod(self):
      print('Call parent method')
 
class Child(Parent): # Define subclasses
   def myMethod(self):  ### rewrite myMethod
      print('Call subclass method')
 
c = Child()          # Subclass instance
c.myMethod()         # Subclass call override method

Execute the above code and the output results are as follows:

Call subclass method

Foundation overload method

The following table lists some general functions that can be overridden in their own classes:

Serial numberMethod, description & simple call
1 __init__ ( self [,args...] )
Constructor
Simple call method: obj = className(args)
2 __del__( self )
Destruct method to delete an object
Simple call method: del obj
3 __repr__( self )
Converted to a form for the interpreter to read
Simple call method: repr(obj)
4 __str__( self )
Used to convert a value into a human readable form
Simple call method: str(obj)
5 __cmp__ ( self, x )
Object comparison
Simple call method: cmp(obj, x)

Operator overloading

Python also supports operator overloading. Examples are as follows:

#!/usr/bin/python
 
class 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 execution results of the above code are as follows:
Vector(7,8)

Class properties and methods

Private properties of class

__ private_attrs: it starts with two underscores and declares that the attribute is private and cannot be used or accessed directly outside the class. When used in methods inside a class, self__ private_attrs.

Class method

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

Private method of class

__ private_method: it starts with two underscores and declares that the method is private and cannot be called outside the class. Call self. Inside the class__ private_ methods

 

class JustCounter:
    __secretCount = 0  # private variable
    publicCount = 0    # Public variable
 
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print self.__secretCount
 
counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
print counter.__secretCount  # An error is reported. The instance cannot access private variables

Python includes the class name by changing the name:

Traceback (most recent call last):
  File "test.py", line 17, in <module>
    print counter.__secretCount # reports an error. The instance cannot access private variables
AttributeError: JustCounter instance has no attribute '__secretCount'

Python does not allow instantiated classes to access private data, but you can use object_ className__ Attrname (object name. Class name private attribute name) accesses the attribute. Refer to the following examples:

class Rb:
    __site = "www.rb.com"

rb = Rb()
print rb._Rb__site

 

Execute the above code, and the execution results are as follows:

www.rb.com

Description of single underline, double underline and double underline at the beginning and end:

  • __ foo__: Special methods are defined. Generally, system defined names are similar__ init__ () or something.

  • _ foo: variables starting with a single underscore represent protected variables, that is, protected types can only be accessed by themselves and subclasses, not from module import*

  • __ foo: Double underscores represent variables of private type, which can only be accessed by the class itself.

 

Transferred from:

https://www.runoob.com/python/python-object.html

Employee.__doc__: Base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'_module' _ ':' _main ',' _doc ':' base class of all employees', 'empCount': 0, '__init__': <function Employee.__init__ at 0x00A9AC00>, 'displayCount': <function Employee.displayCount at 0x00A9AC48>, 'displayEmployee': <function Employee.displayEmployee at 0x00A9AC90>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>}

Example method

Definition: the first parameter must be an instance object. The parameter name is generally agreed to be "self". It is used to pass the attributes and methods of the instance (or the attributes and methods of the class);

Call: can only be called by instance objects.

Class method

Definition: use decorator @ classmethod. The first parameter must be the current class object. The parameter name is generally agreed as "cls". It is used to pass the properties and methods of the class (the properties and methods of the instance cannot be passed);

Call: both class and instance objects can be called.

Static method

Definition: use decorator @ staticmethod. Parameters are optional. There are no "self" and "cls" parameters, but any attribute and method of class or instance cannot be used in the method body;

Call: both class and instance objects can be called.

 

Static and class methods:

https://www.cnblogs.com/wcwnina/p/8644892.html

 

REF

https://www.cnblogs.com/emanlee/p/15336512.html

 

Added by Pepe on Wed, 19 Jan 2022 10:32:28 +0200