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'}}
1

There are 1 best solutions below

1
J_H On
class Something():
    somevar = None
    def __init__(self, somevar):
        self.somevar = somevar

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 Something is in.

There is a class namespace which, ever since the Something class was defined (at parse time) has a somevar attribute with value None.

Later on, at run time, we create a pair of objects with self.somevar values of 1 and 2. But the class attribute is still None.

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 cls.somevar from within a @classmethod.


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.