Binding methods and unbound methods in Python

Keywords: Python

Binding method

Methods defined in a class can be roughly divided into two categories: bound methods and unbound methods. The binding methods can be divided into object binding methods and class binding methods~

Methods bound to objects

Methods that are not decorated by any decorators in a class are methods bound to objects, which are specially customized for objects.

class Person:
    country = "China"
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def speak(self):
        print(self.name + ', ' + str(self.age))

p = Person('Kitty', 18)
print(p.__dict__)      # {'name': 'Kitty', 'age': 18}
print(Person.__dict__['speak'])  # <function Person.speak at 0x10b81cbf8>

speak is the method bound to an object. This method is not in the object's namespace, but in the class's namespace.
When a method bound to an object is called by an object, there will be a process of automatic value passing, that is, the first parameter (self, generally called self, can also be written as another name) of the current object is automatically passed to the method. If a class call is used, the first parameter needs to be passed manually~

p = Person('Kitty', 18)
p.speak()     # Call through object
Person.speak(p)   # Called by class

Methods bound to classes

The method decorated with @ classmethod in the class is the method bound to the class. This kind of method is specially customized for the class. When a method bound to a class is called by the class name, the class itself is passed as the first parameter of the class method~

class Operate_database():
    host = '192.168.0.5'
    port = '3306'
    user = 'abc'
    password = '123456'

    @classmethod
    def connect(cls):      # It is agreed that the first parameter is named cls, which can also be defined as other parameter names
        print(cls)
        print(cls.host + ':' + cls.port + ' ' + cls.user + '/' + cls.password)

Operate_database.connect()

# Output results:
<class '__main__.Operate_database'>
192.168.0.5:3306 abc/123456

It can also be called through an object. It is only the first parameter passed by default or the class corresponding to this object~

Operate_database().connect()   # Consistent output

Unbound method

The method decorated with @ staticmethod inside the class is called unbound method. There is no difference between this kind of method and ordinary defined function. It is not bound with class or object. Anyone can call it and has no effect of automatic value passing~

import hashlib

class Operate_database():

    def __init__(self, host, port, user, password):
        self.host = host
        self.port = port
        self.user = user
        self.password = password

    @staticmethod
    def get_passwrod(salt, password):
        m = hashlib.md5(salt.encode('utf-8'))
        m.update(password.encode('utf-8'))
        return m.hexdigest()

hash_password = Operate_database.get_passwrod('lala', '123456')  # f7a1cc409ed6f51058c2b4a94a7e1956
# p = Operate_database('192.168.0.5', '3306', 'abc', '123456')
# p.get_passwrod(p.user, p.password)    # Can also be called by object

In short, unbound methods put ordinary methods inside the class~

.................^_^

Posted by markszy on Sat, 30 Nov 2019 17:20:12 -0800