Silver
Silver

Reputation: 1468

Getter or Property function for Class Variables

You can use the @property decorator for instance variables but can you do something similar for class variables?

I have a Config class with config parameters, however I now need some config variables which are functions of the other class variables. For example,

class Config:
    foo = 1
    bar = 2
    @property
    def baz():
        return self.foo + 2*self.bar

print(Config.baz)

This however does not work. It returns <builtin.property object> instead of the return value from calling the function. Any suggestions?

Upvotes: 1

Views: 63

Answers (1)

Duncan
Duncan

Reputation: 95742

Sure you can, but just as the property has to be defined on the class to use it on the instance, you have to define a property on the metaclass to be able to use it directly on the class itself:

class ConfigType(type):
    @property
    def baz(cls):
        return cls.foo + 2*cls.bar

class Config(metaclass=ConfigType):
    foo = 1
    bar = 2

print(Config.baz)

will print 5.

When you do this the property won't be visible on the instances at all, only on the class but you can define it in both places and the two definitions won't interfere:

class ConfigType(type):
    @property
    def baz(cls):
        return cls.foo + 2*cls.bar

class Config(metaclass=ConfigType):
    foo = 1
    bar = 2

    @property
    def baz(self):
        return self.foo + 2*self.bar

config = Config()
config.foo = 3
print(Config.baz, config.baz)

prints 5 7

Upvotes: 2

Related Questions