pythonpython-decorators

Python: how to sum/multiply an int with the value of a @property


The name property stands in the way here, so my searches has been unsuccessful. What I want to accomplice is multiply (sum , subtract, ...) an integer value to a value coming from a property (meaning @property):

class A:
    __att = 3
    @property
    def att():
        return __att
    
    def test_method(self):
        return 3*A.att
        
a = A()
x = a.test_method()

but I get TypeError: unsupported operand type(s) for *: 'int' and 'property'

I understand the meaning of the message: it's sort of trying to multiply an int to a method name instead of its result, but for properties, shouldn't it be transparent? I do not understand what I'm missing here.


Solution

  • If you want a class property, you can stack decorators in Python < 3.13.

    class A:
        __att = 3
        @classmethod
        @property
        def att(cls):
            return cls.__att
    
        def test_method(self):
            return 3*A.att
    

    The value is accessible from a.att or A.att and shared between all instances. The "real" class attribute which the property gets is name-mangled at A._A__att.