我想选择在运行时继承哪个类,无论是A类还是B类,这取决于我在AorB中的init函数的参数。我已经尝试了以下代码,但方法没有按我希望它们重载的方式重载:AorB(“B”)。a()返回A.a()而不是B.a()。如何选择我在运行时继承的类?
更新 从下面的反应我尝试了以下代码。现在我想在C类中继承AorB,但这还不行:
class A(object):
def a(self):
return "I'm A.a"
def b(self):
return "I'm A.b"
class B(object):
def a(self):
return "I'm B.a"
def c(self):
return "I'm B.c"
def AorB(classname, cache={}):
if not classname in cache:
Base = globals()[classname]
class AorB(Base):
def __init__(self):
print(classname)
Base.__init__(self)
cache[classname] = AorB
return cache[classname]()
class C(AorB):
def __init__(self, classname):
AorB.__init__(classname)
if __name__ == "__main__":
a = AorB("A")
print("A.a:", a.a())
print("A.b:", a.b())
b = AorB("B")
print("B.a:", b.a())
print("B.c:", b.c())
c = C("B")
print("C.a:", c.a())
print("C.c:", c.c())
产量
Traceback (most recent call last):
File "classtest.py", line 28, in <module>
class C(AorB):
TypeError: Error when calling the metaclass bases
function() argument 1 must be code, not str
而不是:
A
('A.a:', "I'm A.a")
('A.b:', "I'm A.b")
B
('B.a:', "I'm B.a")
('B.c:', "I'm B.c")
B
('C.a:', "I'm B.a")
('C.c:', "I'm B.c")
答案 0 :(得分:5)
class A(object):
def a(self):
return "I'm A.a"
def b(self):
return "I'm A.b"
class B(object):
def a(self):
return "I'm B.a"
def c(self):
return "I'm B.c"
def make_AorB(Base, classname):
class AorB(Base):
def __init__(self):
print(classname)
Base.__init__(self)
return AorB
def make_C(Base, classname):
class C(Base):
def __init__(self):
Base.__init__(self)
def d(self):
return "I'm C.d"
return C
def make_factory(getbase, make_cls):
def factory(classname):
if not classname in factory.cache:
Base = getbase(classname)
factory.cache[classname] = make_cls(Base, classname)
return factory.cache[classname]()
factory.cache = {}
return factory
AorB = make_factory(lambda classname: globals()[classname], make_AorB)
C = make_factory(lambda classname: AorB.cache[classname], make_C)
if __name__ == "__main__":
a = AorB("A")
print(a.__class__, a.__class__.__bases__)
print("A.a:", a.a())
print("A.b:", a.b())
b = AorB("B")
print(b.__class__, b.__class__.__bases__)
print("B.a:", b.a())
print("B.c:", b.c())
c = C("B")
print(c.__class__, c.__class__.__bases__)
print("C.a:", c.a())
print("C.c:", c.c())
print("C.d:", c.d())
产量
A
(<class '__main__.AorB'>, (<class '__main__.A'>,))
('A.a:', "I'm A.a")
('A.b:', "I'm A.b")
B
(<class '__main__.AorB'>, (<class '__main__.B'>,))
('B.a:', "I'm B.a")
('B.c:', "I'm B.c")
B
(<class '__main__.C'>, (<class '__main__.AorB'>,))
('C.a:', "I'm B.a")
('C.c:', "I'm B.c")
('C.d:', "I'm C.d")
答案 1 :(得分:0)
我不是100%肯定(你的用例),但是你可以使用type
的变体做类似下面的事情(某些东西是有条件的):
def produce_C(kls, *args, **kwdargs):
return type('C', (globals()[kls],), {})(*args, **kwdargs)
虽然会混淆类型系统...(可能会将类名修改为C_from_A
或C_from_B
- 但是呃)
答案 2 :(得分:0)
以下是您的代码问题(更新后) C不能从AorB继承,这是一个函数:
class C(AorB):
def __init__(self, classname):
AorB.__init__(classname)
由于你想在调用C时对基类进行低音,你可以只做C a 依次调用AorB的函数:
def C(basename):
return AorB(basename)