Python 用另一个类扩展一个类?
我有一个定义Python 用另一个类扩展一个类?,python,python-2.x,Python,Python 2.x,我有一个定义Bird、Eagle和Hawk类的包Eagle和Hawk是Bird的子类 e = Eagle(attr_eagle, attr_bird) print(e.attr_eagle) print(e.attr_bird) 我想向Bird类添加一些属性,但我不想更改定义类的包。我正在考虑创建一个自定义类MyBird e = Eagle(attr_eagle, attr_bird) print(e.attr_eagle) print(e.attr_bird) 由于Eagle继承了Bird
Bird
、Eagle
和Hawk
类的包Eagle
和Hawk
是Bird
的子类
e = Eagle(attr_eagle, attr_bird)
print(e.attr_eagle)
print(e.attr_bird)
我想向Bird
类添加一些属性,但我不想更改定义类的包。我正在考虑创建一个自定义类MyBird
e = Eagle(attr_eagle, attr_bird)
print(e.attr_eagle)
print(e.attr_bird)
由于Eagle
继承了Bird
,e.attr_Bird
运行良好。但是,我需要另一个未包含在Bird
类中的属性,将其命名为attr\u mybird
。我想写一些像:
print(e.attr_mybird)
以下是定义从其他类继承的新类的方式:
class Mybird(Bird):
...
评论后编辑:
如果您想让“普通”Eagle拥有MyEagle属性,您需要修改底层库(为什么不呢?),或者实现您自己的MyEagle。这样的MyEagle可以继承Eagle(并添加您在MyBird中添加的内容);从MyBird继承并添加MyEagle Eagle的优点(如果您不知道库的来源,可能会更难),或者使用多重继承,例如:
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
总之,我要做的是创建您自己的鸟叉库,并直接在那里实现您的更改。如果更多的人可以从中受益,请向library author发出拉(合并)请求。如果不是这样,您可以在尊重原始许可证(并更改软件包名称)的情况下,随时将您的fork发布到内部pypi或“官方”pypi上。请使用您的
MyBird
类的定义更新您的代码。为什么不通过继承来完成呢?在这种情况下,Eagle继承自Bird,所以它有它的和鸟的属性,但不是我的鸟的属性。因此,如果e是Eagle实例,e.attr_mybird将不起作用。