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.
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__)
{'name': 'Kitty', 'age': 18} print(Person.__dict__['speak']) <function Person.speak at 0x10f0dd268>
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('Kitty', 18) p.speak() # 通过对象调用 #输出 Kitty, 18 Person.speak(p) # 通过类调用 #输出 Kitty, 18
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 = '192.168.0.5' port = '3306' user = 'abc' password = '123456' @classmethod def connect(cls): # 约定俗成第一个参数名为cls,也可以定义为其他参数名 print(cls) print(cls.host + ':' + cls.port + ' ' + cls.user + '/' + cls.password) Operate_database.connect()
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 '__main__.Operate_database'> 192.168.0.5:3306 abc/123456
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('utf-8')) # 加盐处理 m.update(password.encode('utf-8')) return m.hexdigest() hash_password = Operate_database.get_passwrod('lala', '123456') # 通过类来调用 print(hash_password) #输出 f7a1cc409ed6f51058c2b4a94a7e1956
p = Operate_database('192.168.0.5', '3306', 'abc', '123456') hash_password = p.get_passwrod(p.user, p.password) # 也可以通过对象调用 print(hash_password) #输出 0659c7992e268962384eb17fafe88364
In short, the unbound method is to put the ordinary method inside the class.
Suppose we now have a requirement that the object instantiated by Mysql can read data from the file settings.py.
# settings.py IP = '1.1.1.10' PORT = 3306 NET = 27
# 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('%s:%s' % (self.ip, self.port)) @classmethod def from_conf(cls): return cls(IP, NET, PORT) @staticmethod def func(x, y): print('不与任何人绑定') @staticmethod def create_uid(): """随机生成一个字符串""" return uuid.uuid1() #学习中遇到问题没人解答?小编创建了一个Python学习交流:711312441 # 默认的实例化方式:类名() obj = Mysql('10.10.0.9', 3307, 27)
obj.tell_info() 10.10.0.9:3307
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 '__main__.Mysql'>>
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
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!