Object-oriented based on python - Part 2

Check out the previous article in the previous article , we mainly introduced the basic ideas and concepts of object-oriented, and how to bind properties and methods to classes and instances. This article mainly introduces class decorators, inheritance, static methods, class methods, etc.

1. Class decorator

The python decorator is a function often used in program development. To understand the decorator, you must first be clear:
1. The function decorator is executed immediately when the module is imported, and the decorated function only runs when it is explicitly called.
2. In python, a function is a special variable, that is, a function can also be passed as a parameter to other functions.
If you don’t know about decorators, you can check them here. Click here to view decorators.

# -*- coding:utf-8 -*-
class Hello:
    def info(self, func):
        func()

s = Hello()

@s.info
def f():
    print("hello world!")

output:

hello world!

As above: the decorator is executed immediately when it is imported, and f() will be passed as a parameter to the func parameter in info.
Complex decorator:

# -*- coding:utf-8 -*-
import time

class Hello:
    def info(self, f):
        print("f:", f)
        def second_func(func):
            def thired_func(*args):
                if f == "1":
                    new_time = time.strftime("%y-%m-%d", time.localtime())
                elif f == "0":
                    new_time = time.strftime("%y-%m-%d", time.localtime())
                print(func.__name__, *args, new_time)

            return thired_func
        return second_func

s = Hello()

@s.info("1")
def f(a, b):
    print("hello world!")

f(1,2)

output:

f: 1
f 1 2 20-04-30

Similarly, in @s.info("1"), 1 is first passed into info as a parameter of info, then f is passed into second_func as a parameter, and finally (1, 2) is passed into third_func as a parameter, layer by layer.

Two, property decorator

The property decorator can disguise the method of the class as the method of calling the property of the class. This is very useful in many cases and can help you write concise and beautiful code.

# -*- coding:utf-8 -*-
class Stu(object):
    __name = "male"
    __age = 0

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self,v):
        if not isinstance(v,int):
            raise ValueError("值错误")
        if v > 130 or v < 0:
            raise ValueError("值错误")
        self.__age = v

    @age.deleter
    def age(self):
        print("删除用户数据")

m = Stu()
m.age = 100
print(m.age)
del m.age

output:

100
删除用户数据

Add the @property decorator on the basis of ordinary methods, such as the age() method above. This is equivalent to a get method, which is used to get the value and decide what code to execute like "result = obj.age". This method has only one self parameter. Write a method with the same name and add the @xxx.setter decorator (xxx means the same name as the above method), such as the second method in the example. This is equivalent to writing a set method to provide an assignment function to determine what code to execute for a statement like "obj.age = ...". Write another method with the same name and add the @xxx.delete decorator, such as the third method in the example. Used to delete the function, which determines what code is executed by a statement such as "del obj.age ".

3. Inheritance

Inheritance: That is, a derived class (derived class) inherits the fields and methods of the base class (base class).
If a class is defined and inherits an existing class, the new class is called a subclass, and the inherited class is called a base class, a parent class, or a super class (Base class, Super class). Benefits of inheritance: code reuse Inheritance is divided into single inheritance and
multiple
inheritance

3.1 Single inheritance

Single inheritance refers to inheriting only one parent class, such as:

# -*- coding:utf-8 -*-
# 类定义
class People:
    # 定义基本属性
    name = ""
    age = 0
    __weight = 0
    # 构造方法
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s 说:我目前年龄 %d 正在学PY" %(self.name, self.age))

# 单继承
class Stu(People):
    grade = ""
    def __init__(self, n, a, w, g):
        People.__init__(self, n, a, w)
        self.grade = g
    # 重写父类的方法
    def speak(self):
        print("%s说:我目前年龄%d正当学PY,我目前是%s年级" % (self.name, self.age, self.grade))

p1 = Stu("lyy", 15, 120, "2")
p1.speak()
p2 = People("md", 45, 75)
p2.speak()

output:

lyy说:我目前年龄15正当学PY,我目前是2年级
md 说:我目前年龄 45 正在学PY

The subclass Syu inherits the methods of the parent class People.

3.2 Multiple inheritance

Multiple inheritance refers to the inheritance of multiple parent classes. In the case of multiple inheritance, one of the problems that must be mentioned is the order of inheritance. Before figuring out the order of inheritance, we need to understand two concepts: depth-first and breadth-first.

depth first and breadth first
In the py2.x version, the classic classes are processed in the order of depth-first,
and the new-style classes are processed in the order of breadth-first; in the py3.

class BaseClass(object):
    def show(self):
        print('BaseClass')

class SubClassA(BaseClass):
    def show(self):
        print('Enter SubClassA')
        super().show()
        print('Exit SubClassA')

class SubClassB(BaseClass):
    def show(self):
        print('Enter SubClassB')
        super().show()
        print('Exit SubClassB')

class SubClassC(SubClassA):
    def show(self):
        print('Enter SubClassC')
        super().show()
        print('Exit SubClassC')

class SubClassD(SubClassB, SubClassC):
    def show(self):
        print('Enter SubClassD')
        super().show()
        print('Exit SubClassD')

d = SubClassD()
d.show()

The inheritance relationship is as shown in the figure below:
insert image description here
output:

Enter SubClassD
Enter SubClassB
Enter SubClassC
Enter SubClassA
BaseClass
Exit SubClassA
Exit SubClassC
Exit SubClassB
Exit SubClassD
[<class '__main__.SubClassD'>, <class '__main__.SubClassB'>, <class '__main__.SubClassC'>, <class '__main__.SubClassA'>, <class '__main__.BaseClass'>, <class 'object'>]

The order is DBCA-BaseClass.
When the order of SubClassD inheritance is changed, such as: class SubClassD(SubClassC, SubClassB):the order of access becomes DCAB-BaseClass
output:

Enter SubClassD
Enter SubClassC
 Enter SubClassA
Enter SubClassB
BaseClass
Exit SubClassB
Exit SubClassA
Exit SubClassC
Exit SubClassD
[<class '__main__.SubClassD'>, <class '__main__.SubClassC'>, <class '__main__.SubClassA'>, <class '__main__.SubClassB'>, <class '__main__.BaseClass'>, <class 'object'>]

4. Static method

Static method: A method without self parameter decorated with @staticmethod is called a static method. The static method of a class can have no parameters and can be called directly using the class name.
Note
1. Static methods cannot call instance variables.
2. There is no need to pass a class or instance when calling. Like the functions we define outside the class, except that the static method can be called through the class or instance.

class Eat:
    name = "jsonwong"
    age = 18
    @staticmethod
    def func():
        print('hello world!')
eat = Eat()
eat.func()

output:

hello world!

Five, class method

Class methods are implemented with the @classmethod decorator.
Note
1. Class methods can only access class variables, not instance variables.
2. Pass the current class object through the cls parameter, without instantiation, and directly access it through the class object [instance name. method name] and the class object instance [class name. method name].

class Eat:
    name = "jsonwong"
    food = "牛肉"
    def __init__(self, food):
        self.food = food
    @classmethod
    def func(cls):
        print('hello world!', cls.food)
eat = Eat("羊肉")
eat.func()

output:

hello world! 牛肉

Note that you can see above that class methods can only access class variables, not instance variables.

6. Proprietary methods of classes

Proprietary method name explain
_init_ Construction method, used when generating objects
_ of _ Analysis function, used when releasing the object
_dict_ Dictionary, record class attribute information
_len_ get length
_mro_ method query
_str_ show to users
_repr_ show to the parser

Guess you like

Origin blog.csdn.net/JaysonWong/article/details/105856085