Chapter 7 object oriented (10): binding method and unbound method (static method)

Posted by JessePHP on Mon, 21 Oct 2019 18:25:10 +0200

What is bound method, unbound method

  • Functions defined internally are divided into two categories:
    • Binding method: it should be called by whoever is bound. Whoever calls will automatically pass in the caller as the first parameter
      • Bound to object method: a method defined within a class that is not decorated by any decorator
      • Methods bound to classes: methods defined within classes decorated with @ classmethod
    • Unbound method (static method): without automatic value passing, it is a common tool in the class.
      • Not bound to class or object
class Foo:
    def __init__(self, name):  # This is actually a way to bind objects.
        self.name = name
        
    def tell(self):  # Methods for binding objects
        print('name is:',self.name)
        
    @classmethod
    def func(cls):  # 
        print(cls)
    
    @staticmethod
    def func1(x, y):  # Unbound method (static method), parameters will not be passed automatically
        return x + y
        

print(Foo.tell)  # We can see that if we call with a class, it is a function type: function.

# Methods for binding objects
f = Foo('a')
print(f.tell)  # As we can see, when an object is called, it is a binding method type: bound method.

# Methods for binding classes
print(Foo.func)  # Calling with a class is also a binding method type: bound method
Foo.func()  # At this time, cls = Foo
# f.func()  # Even an object call is still called by its class, cls = Foo. However, the binding to the class should be called by the class, so it is not written in this way.

# The unbound method can be used as a general function.
print(Foo.func1)  # Is a function type: function
print(f.func1)  # Is a function type: function

Application of binding method and unbound method

Let's use the following code example to demonstrate the use of binding methods and unbound methods:

import hashlib
import time

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

class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
        self.id = self.create_id()  # Call unbound method to assign

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

    @classmethod
    def from_conf(cls, conf_dict):  # Here we initialize an object with a dictionary. Since it is called from a class and automatically passes in the class itself as a parameter, it is defined as a method of binding the class.
        obj = cls(
            conf_dict['name'],
            conf_dict['age'],
            conf_dict['sex']
        )
        return obj

    @staticmethod
    def create_id():  # This function does not need to automatically pass in any class and object related parameters, so it is a general parameter, so it is defined as a unbound method.
        m = hashlib.md5(str(time.time()).encode('utf-8'))
        return m.hexdigest()


p1 = People('x', 11, 'female')
time.sleep(0.00005)  # To prevent the id from being the same, we add a delay
p2 = People('y', 10, 'female')
time.sleep(0.00005)

# Instantiate an object with a class binding method
p3 = People.from_conf(dict1)  # Directly call the method of the class to return an object
print(p3.__dict__)

# View the id generated by the unbound method
print(p1.id)
print(p2.id)
print(p3.id)

Execution result:

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

Topics: PHP