我有一个类,如下所示:
class MyClass(object):
int = None
def __init__(self, *args, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
def get_params(self):
return {'int': random.randint(0, 10)}
@classmethod
def new(cls):
params = cls.get_params()
return cls(**params)
我希望能够做到:
>>> obj = MyClass.new()
>>> obj.int # must be defined
9
我的意思是没有创建的新实例MyClass
,但显然它不是那么简单,因为调用MyClass.new()
抛出TypeError: unbound method get_params() must be called with MyClass instance as first argument (got nothing instead)
有没有什么办法来实现呢? 谢谢