Opinion! Creating Template filters to work with class instance in templates, this works, wondering the most "django" optimal way?
Accessing class methods in templates, this works but was wondering if their was a better way?
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):
from django import template register = template.Library() @register.filter def class_get_method(value, method): f = method.split('.') method = f del f p = getattr(value, method) if f: return p(*f) else: return p()
in template, lets say content is a class instance
class Something(): somevar = None def __init__(self, somevar): self.somevar = somevar
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
Something is in.
There is a class namespace which,
ever since the
Something class was defined (at parse time)
somevar attribute with value
Later on, at run time, we create a pair of objects
self.somevar values of
But the class attribute is still
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 as
from within a
Notice that class attribute
somevar can be initialized
as a mutable data structure, such as a dict.
And then both classmethods and ordinary methods can mutate it.