【发布时间】:2019-01-19 15:00:55
【问题描述】:
我想通过 Bar 类扩展 Foo 类,我遇到的问题是我无法以通常的方式 (class Foo(Bar)) 扩展它,因为 Bar 类有点动态生成。
我做了这个小例子来说明我想要的结果:
class Bar:
def super_cool_function():
print("Cool")
class Foo:
def __init__(self, another_class):
# I want to extend Foo by another_class
# Desired result
foobar = Foo(Bar)
foobar.super_cool_function()
这又是不是我要找的东西:
class Foo(Bar):
pass
foobar = Foo()
foobar.super_cool_function()
【问题讨论】:
-
什么时候知道
Bar?class Foo(X):工作得很好,即使X是一个变量,而不是父类的字面名称。 -
我应该指出,为了让 Foo 的实例可以调用
super_cool_function,它需要self参数 (def super_cool_function(self):)。我不会编辑您的问题来更正它,因为这会使 abarnert 的答案无效。
标签: python class inheritance closures