Chapter VII of object-oriented (10): non-binding method and binding method (static method)

What is binding method, non-binding approach

  • Function within the definition divided into two categories:
    • Binding method: bind to whom, who should be called. Who will call the caller is automatically passed as the first argument
      • Method bind to the object: not modified any decorator methods defined in the class
      • Method bound to class: @classmethod decorated by a method defined in the class
    • Non-binding method (static method): There is no automatic transfer value is a common tool in class
      • Not tied to an object or class
class Foo:
    def __init__(self, name):  # 这其实就是个绑定对象的方法
        self.name = name
        
    def tell(self):  # 绑定对象的方法
        print('name is:',self.name)
        
    @classmethod
    def func(cls):  # 
        print(cls)
    
    @staticmethod
    def func1(x, y):  # 非绑定方法(静态方法),不会自动传参
        return x + y
        

print(Foo.tell)  # 我们可以看到用类调用的话,就是个函数类型:function

# 绑定对象的方法
f = Foo('a')
print(f.tell)  # 我们可以看到,对象调用的话,是一个绑定方法类型:bound method

# 绑定类的方法
print(Foo.func)  # 用类调用也是一个绑定方法类型:bound method
Foo.func()  # 这时候cls = Foo
# f.func()  # 即使是对象调用依然是其类调用的,即cls = Foo。不过绑定到类的应该由类来调用,所以不这么写

# 非绑定方法,使用的时候就当一般的函数来用就可以了。
print(Foo.func1)  # 是个函数类型:function
print(f.func1)  # 是个函数类型:function

Application method binding and non-binding approach

We use the following code examples to demonstrate it using the binding method, a non-binding approach:

import hashlib
import time

dict1 = {'name': 'a', 'age': 20, 'sex': '男'}

class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
        self.id = self.create_id()  # 调用非绑定方法来赋值

    def tell_info(self):
        print('Name:%s Age:%s Sex:%s' % (self.name, self.age, self.sex,))

    @classmethod
    def from_conf(cls, conf_dict):  # 这里我们用字典初始化了一个对象,由于是从类调用,自动传入类本身作为参数,所以定义成绑定类的方法
        obj = cls(
            conf_dict['name'],
            conf_dict['age'],
            conf_dict['sex']
        )
        return obj

    @staticmethod
    def create_id():  # 这个函数并不需要自动传入任何类和对象有关的参数,所以是一个一般参数,所以定义成非绑定方法
        m = hashlib.md5(str(time.time()).encode('utf-8'))
        return m.hexdigest()


p1 = People('x', 11, '女')
time.sleep(0.00005)  # 为了防止id一样,我们加一个延迟
p2 = People('y', 10, '女')
time.sleep(0.00005)

# 用类绑定方法实例化一个对象
p3 = People.from_conf(dict1)  # 直接调用类的方法返回一个对象出来
print(p3.__dict__)

# 查看非绑定方法生成的id
print(p1.id)
print(p2.id)
print(p3.id)

Results of the:

{'name': 'a', 'age': 20, 'sex': '男', 'id': 'e3c89723b7de3f6bc7b7438af764b04d'}
0a254de3e2ac2d55795cb1e2834ca031
6352348ab3ce1217e21895010ee1f202
e3c89723b7de3f6bc7b7438af764b04d

Guess you like

Origin www.cnblogs.com/py-xiaoqiang/p/11210459.html