如何在Python中动态添加类方法 [英] How to add a classmethod in Python dynamically

查看:534
本文介绍了如何在Python中动态添加类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 3. 我知道@classmethod装饰器.另外,我知道可以从实例中调用类方法.

I'm using Python 3. I know about the @classmethod decorator. Also, I know that classmethods can be called from instances.

class HappyClass(object):
    @classmethod
    def say_hello():
        print('hello')
HappyClass.say_hello() # hello
HappyClass().say_hello() # hello

但是,我似乎无法动态创建类方法并不能从实例中调用它们.假设我想要类似的东西

However, I don't seem to be able to create class methods dynamically AND let them be called from instances. Let's say I want something like

class SadClass(object):
    def __init__(self, *args, **kwargs):
        # create a class method say_dynamic

SadClass.say_dynamic() # prints "dynamic!"
SadClass().say_dynamic() # prints "dynamic!"

我玩过cls.__dict__(会产生异常)和setattr(cls, 'say_dynamic', blahblah)(这只会使小东西可以从类而不是实例中调用).

I've played with cls.__dict__ (which produces exceptions), and with setattr(cls, 'say_dynamic', blahblah) (which only makes the thingie callable from the class and not the instance).

如果您问我为什么,我想做一个懒惰的类财产.但是不能从实例中调用它.

If you ask me why, I wanted to make a lazy class property. But it cannot be called from instances.

@classmethod
def search_url(cls):
    if  hasattr(cls, '_search_url'):
        setattr(cls, '_search_url', reverse('%s-search' % cls._meta.model_name))
    return cls._search_url

可能是因为尚未从类中调用该属性...

Maybe because the property hasn't been called from the class yet...

总而言之,我想添加一个惰性方法,可以从实例中调用.以一种优雅的(nottoomanylines)的方式?

In summary, I want to add a lazy, class method that can be called from the instance... Can this be achieved in an elegant (nottoomanylines) way?

有什么想法吗?

我如何实现的

对不起,我的例子很糟糕:\

Sorry, my examples were very bad ones :\

无论如何,最后我还是这样...

Anyway, in the end I did it like this...

@classmethod
def search_url(cls):
    if not hasattr(cls, '_search_url'):
        setattr(cls, '_search_url', reverse('%s-search' % cls._meta.model_name))
    return cls._search_url

setattr确实有效,但是在测试时我犯了一个错误...

And the setattr does work, but I had made a mistake when testing it...

推荐答案

我是如何实现的:

@classmethod
def search_url(cls):
    if not hasattr(cls, '_search_url'):
        setattr(cls, '_search_url', reverse('%s-search' % cls._meta.model_name))
    return cls._search_url

这篇关于如何在Python中动态添加类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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