SoFunction
Updated on 2024-11-15

Bound and unbound methods for classes and objects in Python explained in detail

Methods defined in a class can be broadly categorized into two types: bound methods and unbound methods. Bound methods can be further divided into methods bound to objects and methods bound to classes.

I. Binding methods

1 Binding methods for objects

Methods in a class that are not modified by any decorator are methods bound to an object, which are customized for the object.

class Person:
    country = "China"

    def __init__(self, name, age):
         = name
         = age

    def speak(self):
        print( + ', ' + str())


p = Person('Kitty', 18)
print(p.__dict__)
{'name': 'Kitty', 'age': 18}

print(Person.__dict__['speak'])
<function  at 0x10f0dd268>

speak is the method bound to the object, which is not in the object's namespace, but in the class namespace.

Calling a method bound to an object through an object will have an automatic passing process, i.e., the current object is automatically passed to the first parameter of the method (self, which is generally called self, or can be written as something else); if you are using a class call, the first parameter needs to be passed manually.

p = Person('Kitty', 18)
()  # Called by object
# Output
Kitty, 18

(p)  # Called by class
# Output
Kitty, 18

2 Class Binding Methods

Methods in a class that are qualified with @classmethod are methods that are bound to the class. This type of method is customized specifically for the class. When calling a method bound to a class by its name, the class itself is passed as an argument to 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):  # The first parameter is conventionally named cls, but can be defined as any other parameter.
        print(cls)
        print( + ':' +  + ' ' +  + '/' + )


Operate_database.connect()

exports

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

It can also be called through an object, except that the first parameter passed by default is still the class corresponding to this object.

Operate_database().connect()  # The output is consistent

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

II. Unbound methods

Methods qualified with @staticmethod inside a class are unbound methods, which are indistinguishable from commonly defined functions, are not bound to a class or object, can be called by anyone, and do not have the effect of automatic value passing.

import hashlib


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

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


hash_password = Operate_database.get_passwrod('lala', '123456')  # Called by class
print(hash_password)

# Output
f7a1cc409ed6f51058c2b4a94a7e1956
p = Operate_database('192.168.0.5', '3306', 'abc', '123456')
hash_password = p.get_passwrod(, )  # It can also be called from an object
print(hash_password)
# Output
0659c7992e268962384eb17fafe88364

In short, unbound methods are ordinary methods placed inside the class.

III. Exercises

Suppose we now have a requirement to make Mysql instantiate objects that can read data from a file.

# 
IP = '1.1.1.10'
PORT = 3306
NET = 27
# 
import uuid


class Mysql:
    def __init__(self, ip, port, net):
         = self.create_uid()
         = ip
         = port
         = net

    def tell_info(self):
        """View ip address and port number."""
        print('%s:%s' % (, ))

    @classmethod
    def from_conf(cls):
        return cls(IP, NET, PORT)

    @staticmethod
    def func(x, y):
        print('Not tied to anyone')

    @staticmethod
    def create_uid():
        """Generate a random string."""
        return uuid.uuid1()

No one to answer your questions in #learning? I have created a Python learning exchange: 711312441
# Default instantiation: class name()
obj = Mysql('10.10.0.9', 3307, 27)
obj.tell_info()

10.10.0.9:3307

1 Summary of Binding Methods

If the function body code needs to use an externally passed-in class, the function should be defined as a method bound to the class

If the function body code needs to use an externally passed in object, the function should be defined as a method bound to an object

# A new way to instantiate: reading configuration from a configuration file to complete instantiation
obj1 = Mysql.from_conf()
obj1.tell_info()

# Output
1.1.1.10:27



print(obj.tell_info)
# Output
<bound method Mysql.tell_info of <__main__.Mysql object at 0x10f469240>>



print(obj.from_conf)
# Output
<bound method Mysql.from_conf of <class '__main__.Mysql'>>

2 Summary of unbound methods

If the function body code requires neither an externally passed class nor an externally passed object, the function should be defined as an unbound method/normal function

(1, 2)
# Output
Not tied to anyone


(3, 4)
# Output
Not tied to anyone


print()
# Output
<function  at 0x10f10e620>


print()
# Output
<function  at 0x10f10e620>


print()
# Output
a78489ec-92a3-11e9-b4d7-acde48001122

Above is the Python class and object binding and unbinding methods explained in detail, more information about Python class object binding please pay attention to my other related articles!