Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用另一个类扩展一个类?_Python_Python 2.x - Fatal编程技术网

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将不起作用。