我想实现以下结构:
class Case(nx.Graph):
def __init__(self, case):
if case == 1:
self = Case1()
if case == 2:
self = Case2()
class Case1(Case):
def __init__(self):
super(Case1, self).__init__()
print "Case1"
class Case2(Case):
def __init__(self):
super(Case2, self).__init__()
print "Case2"
例如,如果我创建以下对象:
graph = Case(1)
应创建类Case1
的新Object。在__init__
班Case1
中,super()
功能应调用__init__
的{{1}}函数。
如果我运行该代码,结果应该是名为“graph”的networkx.Graph()
对象,并且应该打印networkx.Graph
。
答案 0 :(得分:1)
当您说self = ...
时,您只是重新定义self
。你没有改变它。要做你想做的事,请改用__new__
:
class Case(nx.Graph):
def __new__(self, case):
if case == 1:
return Case1()
elif case == 2:
return Case2()
else:
raise ValueError("Invalid argument")
但是,你真的不应该这样做。如果您想为不同的案例设置不同的实例,请在创建实例时执行此操作,但是为了工作,类不应依赖于其子类。
答案 1 :(得分:0)
这样做的一种方法是不为子类调用__init__
,而是将它们放在一个单独的方法中,即setup
并重写__class__
属性:
class Case(object):
def __init__(self, case):
# Maybe even call the init of the superclass:
super(Case, self).__init__()
# Do the setup that is common to all Cases:
self.setup()
# Change the class of the instance depending on your case:
if case == 1:
self.__class__ = Case1 # No () here!
elif case == 2:
self.__class__ = Case2
else:
raise ValueError()
# Call the setup of the subclass
self.setup()
def setup(self):
print('Setup of Case called.')
class Case1(Case):
def setup(self):
print('Setup of Case1 called.')
class Case2(Case):
def setup(self):
print('Setup of Case2 called.')
当我尝试创建Case1
:
a = Case(1)
打印:
Setup of Case called.
Setup of Case1 called.
但是甚至可能有适当的(内置模块,包)配方来做这样的事情。
答案 2 :(得分:0)
这是一个经典的工厂模式。我将使用静态方法实现它,如下所示:
class Case(object):
@staticmethod
def factory(case):
if case == 1:
return Case1()
if case == 2:
return Case2()
raise NotImplementedError('Unknown case: %r'%case)
class Case1(Case):
def __init__(self):
super(Case1, self).__init__()
print "Case1"
class Case2(Case):
def __init__(self):
super(Case2, self).__init__()
print "Case2"
您可以根据args进行扩展以传递给初始值设定项。在使用中,您可能会看到以下内容:
c1 = Case.factory(1)
c2 = Case.factory(2)
print type(c1), type(c2)
Case.factory(3)
输出看起来像这样:
Case1
Case2
<class '__main__.Case1'> <class '__main__.Case2'>
Traceback (most recent call last):
File "<string>", line 36, in <module>
File "<string>", line 19, in factory
NotImplementedError: Unknown case: 3