I am using Python 3. I know about the @classmethod decorator. In addition, I know that classmethods can be called from instances.
class HappyClass(object):
@classmethod
def say_hello():
print('hello')
HappyClass.say_hello()
HappyClass().say_hello()
However, I cannot dynamically create class methods and allow them to be called from instances. Say I want something like
class SadClass(object):
def __init__(self, *args, **kwargs):
SadClass.say_dynamic()
SadClass().say_dynamic()
I played with cls.__dict__(which throws exceptions) and with setattr(cls, 'say_dynamic', blahblah)(which only makes the object called from the class, not the instance).
If you ask me why, I wanted to create 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
Perhaps because the property has not yet been called from a class ...
, , ... (nottoomanylines) ?
?
, :\
, ...
@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 , ...