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

Posted by 007brendan on Stack Overflow See other posts from Stack Overflow or by 007brendan
Published on 2010-03-23T21:15:29Z Indexed on 2010/03/23 22:23 UTC
Read the original article Hit count: 261

Filed under:
|
|

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')

© Stack Overflow or respective owner

Related posts about python

Related posts about inheritance