How to add a classmethod in Python dynamically

前端 未结 4 1298
無奈伤痛
無奈伤痛 2021-02-14 04:15

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

class HappyClass(object):
    @classme         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 04:42

    You can add a function to a class at any point, a practice known as monkey-patching:

    class SadClass:
        pass
    
    @classmethod
    def say_dynamic(cls):
        print('hello')
    SadClass.say_dynamic = say_dynamic
    
    >>> SadClass.say_dynamic()
    hello
    >>> SadClass().say_dynamic()
    hello
    

    Note that you are using the classmethod decorator, but your function accepts no arguments, which indicates that it's designed to be a static method. Did you mean to use staticmethod instead?

提交回复
热议问题