Python:如何从同一类的类方法调用实例方法 [英] Python: How to call an instance method from a class method of the same class

查看:187
本文介绍了Python:如何从同一类的类方法调用实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程如下:

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

  1. get_param设为类方法并修复对其的引用
  2. 具有__init__调用get_param,因为它是实例方法
  1. make get_param a class method and fix references to it
  2. have __init__ call get_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:如何从同一类的类方法调用实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆