NI6*_*NI6 3 python python-attrs
我有两个非常类似的类:A和B:
import attr
@attr.s
class A(object):
x = attr.ib()
y = attr.ib()
@attr.s
class B(object):
x = attr.ib()
z = attr.ib()
y = attr.ib(default=None)
Run Code Online (Sandbox Code Playgroud)
如您所见,它们共享2个属性(x和y),但在类A中,y属性是位置,而在B中它是可选的.
我想在一个超类中对这些类进行分组,但如果我尝试使类继承自类AI,则会出现以下错误:
SyntaxError: duplicate argument 'y' in function definition
Run Code Online (Sandbox Code Playgroud)
添加了用于引发错误的代码:
@attr.s
class A(object):
x = attr.ib()
y = attr.ib()
@attr.s
class B(A):
z = attr.ib()
y = attr.ib(default=None)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:是否可以使用attrs模块将这些类组合在一个超类中?如果不是,你会建议我将它们分组为"旧时尚"方式(我自己实施init方法)吗?
非常感谢!
我不清楚你期望的行为是什么?如果你想覆盖A y,我有好消息,因为这应该适用于昨天刚刚发布的第17.3集:
>>> @attr.s
... class A(object):
... x = attr.ib()
... y = attr.ib()
...
...
... @attr.s
... class B(A):
... z = attr.ib()
... y = attr.ib(default=None)
>>> B(1, 2)
B(x=1, z=2, y=None)
Run Code Online (Sandbox Code Playgroud)