【问题标题】:Python attrs - positional attribute in super class while optional in sub classPython attrs - 超类中的位置属性,而子类中的可选属性
【发布时间】:2018-04-22 06:11:48
【问题描述】:

我有 2 个非常相似的课程: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)

如您所见,它们共享 2 个属性(x 和 y),但在 A 类中,y 属性是位置属性,而在 B 中是可选的。

我想将这些类归为一个超类,但如果我尝试让 B 类从 A 类继承,我会收到以下错误:

SyntaxError: duplicate argument 'y' in function definition

添加了我用来引发错误的代码:

@attr.s
class A(object):
    x = attr.ib()
    y = attr.ib()


@attr.s
class B(A):
    z = attr.ib()
    y = attr.ib(default=None)

所以我的问题是:是否可以使用 attrs 模块将这些类分组到一个超类中?如果不是,您是否建议我像“旧时尚”那样将它们分组(我自己实现 init 方法)?

非常感谢!

【问题讨论】:

  • 目前想到的最好的事情是让两个类都继承自定义属性 x 的类 C

标签: python python-attrs


【解决方案1】:

我不完全清楚你期望什么行为?如果你想覆盖 A 的 y,我有个好消息,因为这应该适用于昨天刚刚发布的 attrs 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)

【讨论】:

  • 这正是我想要的。抱歉,如果不清楚。非常感谢您的更新!
  • 太棒了!感谢 attrs 库:)
猜你喜欢
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 2020-11-10
  • 1970-01-01
  • 2017-08-03
相关资源
最近更新 更多