Accessing class methods in templates, this works but was wondering if their was a better way?
someclass
class Something():
somevar = None
def __init__(self, somevar):
self.somevar = somevar
def set_somevar(self, newvar):
self.somevar = newvar
def set_weird_and_somevar(self, weird, somevar):
self.weird = weird
self.somevar = somevar
def get_tag(self, tag):
templateTag
from django import template
register = template.Library()
@register.filter
def class_get_method(value, method):
f = method.split('.')
method = f[0]
del f[0]
p = getattr(value, method)
if f:
return p(*f)
else:
return p()
in template, lets say content is a class instance
{{content|class_get_method:'set_weird_and_somevar.wenday_adams.nothervar'}}
Yikes!
Don't do that.
The Turing machine you describe has well-defined semantics. But python engineers don't write such code, because it leads to maintenance headaches.
Python is all about namespaces.
There is a global namespace, which
Somethingis in.There is a class namespace which, ever since the
Somethingclass was defined (at parse time) has asomevarattribute with valueNone.Later on, at run time, we create a pair of objects with
self.somevarvalues of1and2. But the class attribute is stillNone.This is perfectly well defined. The machine won't become confused. But you or future maintenance engineers very likely will.
Choose a different name for the class attribute, please. Reference it as
Something.somevar, or ascls.somevarfrom within a@classmethod.Notice that class attribute
somevarcan be initialized as a mutable data structure, such as a dict. And then both classmethods and ordinary methods can mutate it.