Python object oriented

Posted by leon_zilber on Wed, 26 Jan 2022 20:09:37 +0100

Python object oriented

1. Members are divided into three categories

1.1 variables

1.1.1 instance variables and class variables
  • class Foo:
        # Class variable (static field)
        country="China"# The values in each object are the same.
        # method
        def __init__(self,name):
            self.name=name     # Instance variable, field
    
        # method
        def func(self):
            print(self.country)
            
            print(Foo.country)# Recommended use
    
    obj1=Foo('Zhang Beihai')
    obj2=Foo('Taylor')
    print(obj1.name,obj1.country,Foo.country)# obj1.country is not set. The value of the class is taken by default
    obj2.country='U.S.A'
    # Class variables can be accessed directly through classes
    print(obj2.name,obj2.country,Foo.country)
    
  • Guidelines:

    • When accessing instance variables (fields), use object access, that is, obj name.
    • When accessing class variables (static fields), use class methods, namely foo Country. Only use the object when it is really inconvenient.
  • The usage scenario of class variables is: when there are common fields in all objects and they need to be modified or deleted, instance variables (fields) can be extracted into class variables (static fields).

1.1.2 private variables
  • Private variables are also divided into two types: private class variables and private instance variables

  • class Foo:
        __country="China"
        def __init__(self,name):
            self.__name=name #Private instance variable, field
            self.age=123
    
        def func(self):
            print(self.__name)
            print(Foo.__country)
    
    obj=Foo('Cheng Xin')
    # print(obj.__name) # Error reporting: AttributeError:'Foo' object has no attribute '__name'
    # print(Foo.__country)
    obj.func()
    
  • Private member variables are less used in Python. It is characterized by external inaccessibility. Special writing methods can also be obtained. Generally not.

1.2 method

  • classification
    • Example method
    • Static method
    • Class method
  • Private method
    • Private instance method
    • Private static method
    • Private class method
1.2.1 example method
  • Function must contain self,
  • Generally called by object
1.2.2 static method
  • When writing:

    • Write @ staticmethod on the method
    • Optional parameters
  • When called:

    • Class Method name ()
    • Object Method name () # not recommended
  • Usage scenario: static methods can be used without using the values encapsulated in the object.

  • class Foo:
        def __init__(self,name):
            self.name=name
    
        # Example method
        def func(self):
            print(self.name)
    
        @staticmethod
        def display():
            print(666)
    
    obj=Foo("logic")
    Foo.display()# Class calls are generally used
    
Class 1.2.3 method
  • # -*- coding: utf-8 -*-
    '''
    @Time    : 2022/1/23 13:18
    @Author  : ziqingbaojian
    @File    : 03.method.py
    '''
    class Foo:
        def __init__(self,name):
            self.name=name
    
        # Example method
        def func(self):
            print(self.name)
        
        # Static method
        @staticmethod
        def display():
            print(666)
    
        # Class method
        @classmethod
        def show(cls,x1,x2):
            print(cls,x1,x2)
    
    # obj=Foo("logic")
    # Foo.display()# Class calls are generally used
    
    Foo.show(1,8)
    
    • Supplement: self stands for value object, and cls stands for class.
  • When defining:

    • Write @ classmethod on the method
    • Contains at least one cls parameter
  • When executing:

    • Class name Method name; By default, it will be in the value transfer parameters of the current class
  • Usage scenario:

    • If the current class will be used in the method, you can use the class method. The simple interest mode may use the corresponding class method.
  • Class methods are particularly similar to static methods. There is no need to instantiate when calling.

1.2.4 use of private methods
# -*- coding: utf-8 -*-
'''
@Time    : 2022/1/23 13:18
@Author  : ziqingbaojian
@File    : 03.method.py
'''
class Foo:
    def __init__(self,name):
        self.name=name

    # Example method
    def func(self):
        print(self.name)

    def __f1(self,args):
        print("Private method")
    # Static method
    @staticmethod
    def __display():
        print("Private static method")
    @staticmethod
    def get_display():
        Foo.__display()
    # Class method
    @classmethod
    def show(cls,x1,x2):
        print(cls,x1,x2)

# obj=Foo("logic")
# Foo.display()# Class calls are generally used

Foo.get_display()

1.3 properties

class Foo:

    @property
    def start(self):
        return 1
    @property
    def end(self):
        return 2

obj=Foo()
print(obj.start)
print(obj.end)

Transform the method into an attribute, that is, the method is usually called without ().

  • When writing:
    • Write @ property above the method
    • The method parameter has only one self
  • When called:
    • Unordered parentheses, using objects method
  • Application scenario:
    • For simple methods, you can use @ property when there is no need to pass parameters and there is a return value
  • Attributes can also be divided into common and private. Similar to variables and methods

Note: private members of a class cannot be used in inherited subclasses.

2. Combination (modeling)

2.1 nesting of objects

# -*- coding: utf-8 -*-
'''
@Time    : 2022/1/23 14:02
@Author  : ziqingbaojian
@File    : 04.Combinatorial modeling.py
'''

class School:
    def __init__(self,name,addres):
        self.name=name
        self.addres=addres

obj1=School("Asia Fleet ",'Natural selection number')
obj2=School("Asia Fleet ",'Blue space number')


class Teacher:
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.__salary=salary
        self.school=None
t1=Teacher("Zhang Beihai",30,10000)
t2=Teacher("Chu Yan",20,30000)
t1.school=obj1
t2.school=obj2
# Check the captain's ship, nested view
print(t1.school.name)
print(t1.school.addres)

2.2 actively calling members of other classes

class Base:
    def f1(self):
        print("5 Functions")


class Foo(object):
    def f1(self):
        Base.f1(self)
        print("3 Multiple functions")
        
  • Pass the class name The instance method () needs to pass parameters manually and pass in self

  • obj=Base()
    Base.f1(obj)# Manual parameter transfer
    

2.3 inheritance call

class Base:
    def f1(self):
        print("5 Functions")


class Foo:
    def f1(self):
        super().f1()
        print("3 Functions")

class Info(Foo,Base):
    pass

obj=Info()
obj.f1()
# Correct execution

# obj=Foo()
# obj.f1() reports an error because super() in the class represents the next in the current inheritance order. Not just the parent of the current class
  • super() indicates the next in the current inheritance order. Not just the parent of the current class

3. Special members

3.1 common double sliding line method

# -*- coding: utf-8 -*-
'''
@Time    : 2022/1/23 20:41
@Author  : ziqingbaojian
@File    : 06.Special member.py
'''
class Foo:
    # Initialization method class name () is executed automatically
    def __init__(self,name,age):
        print("Object initialization started")
        self.name=name
        self.age=age
    # Object () executes automatically
    def __call__(self, *args, **kwargs):
        print(args,kwargs)

    # Automatic execution of object [xxx]
    def __getitem__(self, item):
        print(item)
        return 1

    # Automatic execution of object [xxx]=11
    def __setitem__(self, key, value):
        print(key,value)
        # This method does not return a value

    def __delitem__(self, key):
        print(1)

    # Realize the operation of adding objects to objects
    def __add__(self, other):
        return self.age+other.age


    def __enter__(self):
        print("have access to with Context management, return value is as Subsequent value reception")
        return 123

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(456)

obj1=Foo("ah",20)
obj1(1,23,3,k1="12")
res=obj1['123']
print(res)
obj1['k1']="v1"
obj1.__delitem__('123')
list
with obj1 as f:
    print(f)
    print("In execution")

3.2 construction method

class Foo:
    def __init__(self,name):
        self.name=name
        print(2)
    def __new__(cls, *args, **kwargs):
        '''
        Returns the name of an empty object init Perform initialization assignment
        :param args:
        :param kwargs:
        '''
        print(1)
        return object.__new__(cls)

obj=Foo('0')

explain:

__ init__ It is generally called initialization method__ new__ Is the way to actually create objects. The two methods are similar to the construction methods in other languages.

3.3 use of common special methods

  1. __ dict__ method
  • class Foo:
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
    obj=Foo('Zhang Beihai','230')
    print(obj.__dict__)#Returns the instance variable as a dictionary
    
  • Supplement:

    • Class__ dict__, It will return member information including functions, which is less used.
  1. __ str__ method
  • class Foo:
        def __init__(self,name,age):
            self.name=name
            self.age=age
        def __str__(self):
            return "Print the object and I'll execute it"
    obj=Foo('Zhang Beihai','230')
    print(obj)
    
  • Similar to the toString() method in Java.

  • Supplement__ repr__ method

    • __ str__ Internal call__ repr__. When there is no__ str__, But there are__ repr__, It is executed when the object is printed. General use__ str__ More methods

4. Class constraints

4.1 actively throw exceptions

class Foo:
    def send(self):
        # If an exception is thrown, the subclass must override the method if it wants to call
        raise NotImplemented(".send() must be overrideen")
    def func(self):
        print("Normal execution")
class Bar(Foo):
    pass
obj=Bar()
obj.func()
obj.send()

4.2 abstract classes and abstract methods

  • Supplement:

    • Python language does not contain the data types of interfaces, but contains abstract classes and abstract methods.
    • Java contains abstract classes and abstract methods, and the methods in the interface must be abstract methods.
  • from abc import ABCMeta,abstractmethod
    
    
    class Foo(metaclass=ABCMeta):
    
        def func(self):
            print(123)
    
        @abstractmethod
        def send(self):
            pass
    
    
    class Bar(Foo):
        def send(self):
            print("Hello world")
    obj= Bar()
    obj.send()
    
  • Note: in Python language, the first method is usually used to handle NotImplemented exceptions without defining relevant abstract classes. Abstract classes and abstract methods are not commonly used.

5. Supplement of multi inheritance

  • Default: first find the parent class on the left and then the parent class on the right.
class A(object):
    pass

class B(object):
    def f1(self):
        print("B.f1")

class C(A,B):
    pass

obj=C()
obj.f1()

5.1 classic and new

  • python2.2

    • Classic class:
    • New class: if you or your predecessors inherit the object, this class is a new class.
  • Python 3 is full of new classes.

  • Difference: the search process is different.

    • Classic class: one goes to black; Depth first
    • New class: C3 algorithm is adopted.
  • Supplement:

    View inheritance relationships.

    # Syntax: class__ mro__
    print(E.__mro__)
    

    • Note: super is to follow__ mro__ Execution sequence.
    • Not included in Python 2__ mro__ method.

5.2 C3 algorithm

  • Simple new class (memory), complex when using C3 algorithm.

Topics: Python