
在#%#$#%@%@%$#%$#%#%#$%@_23eeeb4347bdd26bfc++6b7ee9a3b755dd中,当我们谈论对象的“地址”时,通常指的是其内存地址,可以通过内置函数id()获取。然而,python并非像c/c++那样直接操作内存地址。对于类方法而言,一个常见的误解是,每次访问同一个类方法时,它都应该指向内存中的同一块区域。但实际上,python中的类方法(以及实例方法)是动态创建的对象。
当通过类(如Parent.func1)访问一个使用@classmethod装饰器定义的函数时,Python的描述符协议会被触发。这个协议负责将一个函数转换为一个“方法对象”,并将其绑定到特定的类或实例。关键在于,每次通过类名访问该方法时,Python都会创建一个新的方法对象。这些新创建的方法对象拥有不同的id(),即使它们都指向同一个底层函数实现。
为了验证这一点,我们可以通过id()函数和is运算符进行观察:
class Parent:
@classmethod
def func1(cls):
pass
class Child(Parent):
pass
# 每次访问Parent.func1,都会得到一个不同的方法对象ID
print(f"Parent.func1 ID 1: {id(Parent.func1)}")
print(f"Parent.func1 ID 2: {id(Parent.func1)}")
print(f"Child.func1 ID: {id(Child.func1)}")
# 比较两个方法对象,它们是不同的对象
print(f"Parent.func1 is Parent.func1: {Parent.func1 is Parent.func1}")输出结果会清晰地显示,Parent.func1在两次访问时id不同,且is运算符返回False,这证明了它们是不同的方法对象。
尽管方法对象本身是动态创建的,但它们所封装的底层函数(即@classmethod装饰器下定义的原始函数)是同一个。这个底层函数可以通过方法对象的__func__属性访问。__func__属性指向的是实际的函数定义,它在整个程序生命周期中是唯一的。
立即学习“Python免费学习笔记(深入)”;
class Parent:
@classmethod
def func1(cls):
print("hello func1")
class Child(Parent):
pass
# 比较底层函数,它们是相同的
print(f"Parent.func1.__func__ is Child.func1.__func__: {Parent.func1.__func__ is Child.func1.__func__}")输出将是True,这表明无论是通过Parent还是Child访问func1,它们最终都调用了同一个底层函数实现。
在原始代码示例中,NO_CALCULATE列表试图通过直接存储方法对象来排除某些计算。
class Parent:
# ...
CALCULATE = [func1, func2, func3]
NO_CALCULATE = [] # 存储的是方法对象
class Child(Parent):
NO_CALCULATE = [Parent.func1] # 存储的是Parent.func1方法对象
# ...
@classmethod
def calculate_kpis(cls):
for func in cls.CALCULATE:
# func 是循环中动态获取的方法对象
if func not in cls.NO_CALCULATE: # 这里的比较会失败
func.__get__(cls)()当Child.calculate_kpis方法执行时,for func in cls.CALCULATE循环会动态地获取func1、func2、func3的方法对象。例如,func在某次迭代中可能是Child.func1这个新创建的方法对象。然后,if func not in cls.NO_CALCULATE语句会尝试比较Child.func1(一个新对象)与Parent.func1(NO_CALCULATE中存储的也是一个方法对象,可能也不是当前Child.func1的同一个实例)。由于Python默认的in操作符对于自定义对象会进行身份(is)比较,而这两个方法对象并非同一个实例,因此比较结果为False,导致本应被排除的func1仍然被执行。
为了正确地比较和排除方法,我们应该避免直接比较方法对象本身。有两种更健壮的策略:
比较底层函数 (__func__): 这是最直接的方式,因为它比较的是实际的函数定义。
class Parent:
@classmethod
def func1(cls):
print("hello func1")
@classmethod
def func2(cls):
print("hello func2")
@classmethod
def func3(cls):
print("hello func3")
CALCULATE = [func1, func2, func3]
NO_CALCULATE = []
@classmethod
def calculate_kpis(cls):
excluded_funcs = [f.__func__ for f in cls.NO_CALCULATE]
for func in cls.CALCULATE:
if func.__func__ not in excluded_funcs:
func(cls) # 推荐的调用方式
class Child(Parent):
NO_CALCULATE = [Parent.func1]
if __name__ == "__main__":
print("--- Using __func__ for comparison ---")
c = Child()
c.calculate_kpis()比较方法名 (__name__): 这种方式更具通用性,特别是当需要跨继承链排除方法时。它将方法名作为字符串进行比较,简单直观。
class Parent:
@classmethod
def func1(cls):
print("hello func1 from Parent")
@classmethod
def func2(cls):
print("hello func2 from Parent")
@classmethod
def func3(cls):
print("hello func3 from Parent")
CALCULATE = [func1, func2, func3]
NO_CALCULATE = []
@classmethod
def calculate_kpis(cls):
excluded_names = [f for f in cls.NO_CALCULATE] # NO_CALCULATE现在存储的是字符串
for func in cls.CALCULATE:
if func.__name__ not in excluded_names:
func(cls) # 推荐的调用方式
class Child(Parent):
# 排除Parent.func1,通过其名称
NO_CALCULATE = ["func1"]
if __name__ == "__main__":
print("\n--- Using __name__ for comparison ---")
c = Child()
c.calculate_kpis()在这个修正后的Child类中,NO_CALCULATE列表存储的是方法名字符串,calculate_kpis方法通过比较func.__name__来判断是否执行。这样可以确保即使Child类中重写了func1,只要名称相同,也会被正确排除。
在原始代码中,调用方法使用了func.__get__(cls)()。虽然这种方式可行,但更简洁、更符合Python习惯的类方法调用方式是直接将类作为第一个参数传递给方法对象:func(cls)。
以上就是深入理解Python类方法与描述符:动态对象与比较策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号