【发布时间】:2011-10-31 21:18:26
【问题描述】:
我有两个类,方法为foo:
Foo = type('Foo', (object,), {'foo': lambda s: 'Foo method'})
Bar = type('Bar', (object,), {'foo': lambda s: 'Bar method'})
我还有一些其他类,我需要根据参数将其从上述类之一中子类化。
我的解决方案:
class Subject(object):
def __new__(cls, key):
base = (Foo if key else Bar)
name = cls.__name__ + base.__name__
dict_ = dict(cls.__dict__.items() + base.__dict__.items())
bases = (base, cls)
t = type(name, bases, dict_)
return base.__new__(t)
def bar(self):
return 'Subject method'
测试:
print(Subject(True).foo(), Subject(True).bar())
print(Subject(False).foo(), Subject(False).bar())
输出:
('Foo method', 'Subject method')
('Bar method', 'Subject method')
这个解决方案足够安全吗?还是我需要更多了解?有没有更多的pythonic方式来做这种不规则的事情?
【问题讨论】:
-
创建两个类
SubjectFoo和SubjectBar,分别继承自Foo和Bar,然后编写一个函数Subject检查参数并返回正确的实例班级。以意想不到的方式破坏的可能性要小得多。 -
@ChrisLutz 您在我的解决方案中可以看到哪些意想不到的方式?
标签: python oop inheritance factory subclassing