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

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página