pythoninheritancemetaclass

Should I use a metaclass, class decorator, or override the __new__ method?


Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass, or override the __new__ method to set the properties automagically. I'm just not sure what the "right" way to do it would be.

class Test(object):
    def calculate_attr(self, attr):
        # do calculaty stuff
        return attr

    @property
    def foo(self):
        return self.calculate_attr('foo')

    @property
    def bar(self):
        return self.calculate_attr('bar')

Solution

  • Magic is bad. It makes your code harder to understand and maintain. You virtually never need metaclasses or __new__.

    It looks like your use case could be implemented with pretty straightforward code (with only a small hint of magic):

    class Test(object):
        def calculate_attr(self, attr):
            return something
    
        def __getattr__(self, name):
            return self.calculate_attr(name)