问题描述
我的课程如下:
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)
I mean without creating a new instance of MyClass
, but obviously it's not that simple, because calling MyClass.new()
throws TypeError: unbound method get_params() must be called with MyClass instance as first argument (got nothing instead)
有没有办法做到这一点?谢谢
Is there any way to accomplish so?Thanks
推荐答案
不,您不能也不应该从没有实例的类中调用实例方法.这将非常糟糕.但是,您可以从和实例方法中调用类方法.选项是
No, you can't and shouldn't call an instance method from a class without an instance. This would be very bad. You can, however call, a class method from and instance method. Options are
- 将
get_param
设为类方法并修复对其的引用 - 具有
__init__
调用get_param
,因为它是实例方法
- make
get_param
a class method and fix references to it - have
__init__
callget_param
, since it is a instance method
另外,您可能会对 AttrDict 感兴趣,您正在尝试做.
Also you may be interested in an AttrDict since that looks like what you are trying to do.
这篇关于Python:如何从同一类的类方法调用实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!