Reputation: 200
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.
Upvotes: 1
Views: 128
Reputation: 363304
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
.
Upvotes: 2
Reputation: 411122
You're calling the att
attribute of the class (A.att
):
return 3*A.att
As a class attribute, att
is indeed a property
.
You should call att
using the instance (via self
):
return 3*self.att
This is tangential to your question, but att
also needs to take a self
argument:
@property
def att(self):
return self.__att
Upvotes: 2