使用attr库后Inherited类出现AttributeError: 无params属性的原因
为什么使用attr库后类方法无法找到params属性?
正常运行的代码示例
class base: @classmethod def func(cls): cls.params class inherited(base): params = 2 def my_func(self): inherited.func() obj = inherited() obj.my_func()
这段代码中,inherited类的params是类属性,直接绑定在类本身,因此类方法func通过cls.params可以直接访问到该属性。
使用attr库后的报错代码示例
import attr class base: @classmethod def func(cls): cls.params @attr.s class inherited(base): params = attr.ib() def my_func(self): inherited.func() obj = inherited(2) obj.my_func()
运行后抛出错误:
Traceback (most recent call last): File "test.py", line 16, in <module> obj.my_func() File "test.py", line 13, in my_func inherited.func() File "test.py", line 8, in func cls.params AttributeError: type object 'inherited' has no attribute 'params'
问题原因
当用@attr.s装饰类时,attr.ib()定义的params会被处理为实例属性,而非类属性:
- 第一个示例中,
params = 2是直接绑定在inherited类上的类属性,类方法func里的cls指向inherited类本身,因此能找到该属性。 - 使用attr装饰后,
params只会在创建实例时绑定到具体的实例对象上,类本身并不会拥有这个属性。调用inherited.func()时,cls指向的是inherited类,自然找不到只存在于实例上的params。
如果要让类方法能访问到该值,可选择:
- 将
params改为类属性(例如结合attr.ib的参数配置,不过attr的核心定位是定义实例属性); - 修改类方法逻辑,确保访问的是实例上的属性;
- 将类方法改为实例方法,通过
self.params访问。
内容的提问来源于stack exchange,提问作者structuralengin
相关产品推荐
相关产品推荐

