简体   繁体   中英

How to add classmethod to a python class?

I'm trying to define a generate_username for my User class. (django's user)

The library code will make use of it..

def generate_username(self, user_class):
    """ Generate a new username for a user
    """
    m = getattr(user_class, 'generate_username', None)
    if m:
        return m()

How do I define and add the function generate_username to the User class?
I'm supposed to add a classmethod right?

You add a class method the same way you would monkeypatch an instancemethod but has you have to apply the classmethod decorator to it.

class Test(object):
    pass

@classmethod
def classfunc(cls, attr):
    print(cls, attr)

Test.cf = classfunc

Usage:

>>> Test.cf(33)
<class '__main__.Test'> 33

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM