Python——绑定方法与非绑定方法

绑定方法

  • 特殊之处在于将调用者本身当做第一个参数自动传入

1 绑定给对象的方法

  • 调用者是对象,自动传入的是对象

2 绑定给类的方法

  • 调用者是类,自动传入的是类
# 为类中某个函数加上装饰器@classmethod后,该函数就变成了类的绑定方法

# 配置文件settings.py的内容
HOST='127.0.0.1'
PORT=3306

import settings

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

    def func(self):
        print('%s:%s' %(self.ip,self.port))

    @classmethod # 将下面的函数装饰成绑定给类的方法
    def from_conf(cls):# 从配置文件中读取配置进行初始化
        print(cls)
        return cls(settings.HOST, settings.PORT)

# obj1=Mysql('1.1.1.1',3306)

# 一种新的实例化对象的方法
obj2=Mysql.from_conf()# 调用类方法,自动将类MySQL当作第一个参数传给cls
print(obj2.__dict__)

非绑定方法

# 为类中某个函数加上装饰器@staticmethod后,该函数就变成了非绑定方法,也称为静态方法。
# 静态方法能够被类或对象调用但是只是一个普通函数,因此不会自动传值
import uuid
class MySQL:
    def __init__(self,host,port):
        self.id=self.create_id()
        self.host=host
        self.port=port
    @staticmethod
    def create_id():
        return uuid.uuid1()
    
conn=MySQL(‘127.0.0.1',3306)
'''
print(conn.id) #100365f6-8ae0-11e7-a51e-0088653ea1ec

# 类或对象来调用create_id发现都是普通函数,而非绑定到谁的方法
print(MySQL.create_id)
<function MySQL.create_id at 0x1025c16a8>
print(conn.create_id)
<function MySQL.create_id at 0x1025c16a8>
'''
           
           
# 绑定方法与非绑定方法的使用总结:
'''
若类中需要一个功能,该功能的实现代码中需要引用对象则将其定义成对象方法、
需要引用类则将其定义成类方法、
无需引用类或对象则将其定义成静态方法。
'''

猜你喜欢

转载自www.cnblogs.com/guanxiying/p/12672982.html