【问题标题】:Extend a class with another class?用另一个类扩展一个类?
【发布时间】:2020-10-05 04:03:10
【问题描述】:

我有一个包定义了BirdEagleHawk 类。 EagleHawkBird 的子类。

我想为Bird 类添加一些属性,但我不想更改定义类的包。我正在考虑创建一个自定义类MyBird

e = Eagle(attr_eagle, attr_bird)
print(e.attr_eagle)
print(e.attr_bird)

因为Eagle 继承了Bird,所以e.attr_bird 运行良好。但是我需要另一个不包含在Bird 类中的属性,将其命名为attr_mybird。我想写这样的东西:

print(e.attr_mybird)

【问题讨论】:

  • 请使用您对MyBird 类的定义更新您的代码。
  • 为什么不通过继承来做呢?

标签: python python-2.x


【解决方案1】:

这是定义从其他类继承的新类的方式:

class Mybird(Bird):
    ...

评论后编辑:

如果您希望“普通”Eagle 具有 MyEagle 属性,您需要修改底层库(为什么不呢?),或者也实现您自己的 MyEagle。这样的 MyEagle 可以从 Eagle 继承(并添加您在 MyBird 中添加的内容);从 MyBird 继承并添加使 MyEagle Eagle 的原因(可能更难,如果您不知道 lib 的来源)或使用多重继承,例如:

class AddedFeature:
   ... # implement whatever you want to add to all birs here

class MyBird(Bird, AddedFeature):
   ... # will be Bird with added features from AddedFeature class

class MyEagle(Eagle, AddedFeature):
   ... # will be Eagle with added features from AddedFeature class

总而言之,我要做的就是创建您自己的鸟类库分支并直接在那里实施您的更改。如果更多人可以从中受益,请向图书馆作者提出拉(合并)请求。如果不是这种情况,您可以随时在内部 pypi 或“官方”pypi 上发布您的分叉,同时尊重原始许可证(并更改包名称)

【讨论】:

  • 在这种情况下,Eagle 继承自 Bird,因此它具有其和 Bird 属性,但没有 MyBird 属性。因此,如果 e 是 Eagle 实例,则 e.attr_mybird 将不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 2016-02-28
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多