Python: how to call an instance method from a class method of the same class

I have a class as follows:

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) 

and I would like to be able to:

 >>> obj = MyClass.new() >>> obj.int # must be defined 9 

I mean without creating a new instance of MyClass , but obviously this is not so 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 do this? Thanks

+8
python oop class-method
source share
1 answer

No, you cannot and should not call an instance method from a class without an instance. It will be very bad . You can, however, call the class method from the instance and instance method. Options

  • make get_param class method and fix links to it
  • have a __init__ call to get_param , since this is an instance method

You may also be interested in AttrDict , as this is similar to what you are trying to do.

+5
source share

All Articles