What are the binding and unbinding methods of classes and objects in Python

王林
Release: 2023-05-19 18:39:38
forward
1417 people have browsed it

The methods defined in the class can be roughly divided into two categories: bound methods and non-bound methods. Binding methods can be divided into methods bound to objects and methods bound to classes.

1. Binding method

1 Binding method of object

The method that is not modified by any decorator in the class is the method that is bound to the object. This type Methods are customized specifically for the object.

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__)
Copy after login
{'name': 'Kitty', 'age': 18}

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

speak is a method bound to an object. This method is not in the namespace of the object, but in the namespace of the class.

When calling a method bound to an object through an object, there will be an automatic value transfer process, that is, the current object is automatically passed to the first parameter of the method (self, usually called self, or it can also be written as something else. name); if it is called using a class, the first parameter needs to be passed manually.

p = Person(&#39;Kitty&#39;, 18)
p.speak()  # 通过对象调用
#输出
Kitty, 18

Person.speak(p)  # 通过类调用
#输出
Kitty, 18
Copy after login

2 Class binding method

Methods modified by @classmethod belong to class methods, that is, methods that are bound to classes rather than instances. This type of method is customized specifically for the class. When you call a method bound to a class, the class itself is passed as the first argument to the method.

class Operate_database():
    host = &#39;192.168.0.5&#39;
    port = &#39;3306&#39;
    user = &#39;abc&#39;
    password = &#39;123456&#39;

    @classmethod
    def connect(cls):  # 约定俗成第一个参数名为cls,也可以定义为其他参数名
        print(cls)
        print(cls.host + &#39;:&#39; + cls.port + &#39; &#39; + cls.user + &#39;/&#39; + cls.password)


Operate_database.connect()
Copy after login

Output


192.168.0.5:3306 abc/123456

Pass the object also It can be called, but the first parameter passed by default is still the class corresponding to this object.

Operate_database().connect()  # 输出结果一致

#输出
<class &#39;__main__.Operate_database&#39;>
192.168.0.5:3306 abc/123456
Copy after login

2. Non-binding methods

The methods modified with @staticmethod inside the class are non-binding methods. These methods are no different from ordinary defined functions and are not different from the class or Object binding can be called by anyone, and there is no automatic value transfer effect.

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(&#39;utf-8&#39;))  # 加盐处理
        m.update(password.encode(&#39;utf-8&#39;))
        return m.hexdigest()


hash_password = Operate_database.get_passwrod(&#39;lala&#39;, &#39;123456&#39;)  # 通过类来调用
print(hash_password)

#输出
f7a1cc409ed6f51058c2b4a94a7e1956
Copy after login
p = Operate_database(&#39;192.168.0.5&#39;, &#39;3306&#39;, &#39;abc&#39;, &#39;123456&#39;)
hash_password = p.get_passwrod(p.user, p.password)  # 也可以通过对象调用
print(hash_password)
#输出
0659c7992e268962384eb17fafe88364
Copy after login

In short, the unbound method is to put the ordinary method inside the class.

3. Exercise

Suppose we now have a requirement that the object instantiated by Mysql can read data from the file settings.py.

# settings.py
IP = &#39;1.1.1.10&#39;
PORT = 3306
NET = 27
Copy after login
# test.py
import uuid


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

    def tell_info(self):
        """查看ip地址和端口号"""
        print(&#39;%s:%s&#39; % (self.ip, self.port))

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

    @staticmethod
    def func(x, y):
        print(&#39;不与任何人绑定&#39;)

    @staticmethod
    def create_uid():
        """随机生成一个字符串"""
        return uuid.uuid1()

#学习中遇到问题没人解答?小编创建了一个Python学习交流:711312441
# 默认的实例化方式:类名()
obj = Mysql(&#39;10.10.0.9&#39;, 3307, 27)
Copy after login
obj.tell_info()

10.10.0.9:3307
Copy after login

1 Summary of binding methods

If the function body code needs to use an external class, the function should be defined as a method bound to the class

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

# 一种新的实例化方式:从配置文件中读取配置完成实例化
obj1 = Mysql.from_conf()
obj1.tell_info()

#输出
1.1.1.10:27



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



print(obj.from_conf)
#输出
<bound method Mysql.from_conf of <class &#39;__main__.Mysql&#39;>>
Copy after login

2 Summary of non-binding methods

If the function body code does not need either If the class passed in from the outside does not require the object passed in from the outside, the function should be defined as a non-bound method/ordinary function

obj.func(1, 2)
#输出
不与任何人绑定


Mysql.func(3, 4)
#输出
不与任何人绑定


print(obj.func)
#输出
<function Mysql.func at 0x10f10e620>


print(Mysql.func)
#输出
<function Mysql.func at 0x10f10e620>


print(obj.uid)
#输出
a78489ec-92a3-11e9-b4d7-acde48001122
Copy after login

The above is the detailed content of What are the binding and unbinding methods of classes and objects in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template