3

I'm doing something similar to the following

class Parrot(object): def __init__(self): self.__voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self.__voltage 

However it sees the voltage property as an int so when I call like so

p = Parrot() print(p.voltage()) 

I get

TypeError: 'int' object is not callable 

I've tried with one and two underscored to mangle the voltage property name.

1 Answer 1

10

The whole point of the getter is that it returns the value without being called. p.voltage returns the integer object, so running p.voltage() is equivalent to 100() or something.

There can still be cases where you want to call the value of a property, like if the value is itself a function. But you don't need it here.

Sign up to request clarification or add additional context in comments.

5 Comments

Now how would I do that with a setter? Like codep.voltage(50)code?
p.voltage = 50 - the point of Python properties is to support attributes that use the same syntax as simple attributes but can have arbitrary code that gets executed when they're accessed or set.
You'd use the voltage.setter decorator on another method defined in the class after the getter that is named voltage and expects self and a value argument.
My new favorite feature of python. Thanks!
Properties are great, because they let you skip writing getters and setters in the first place. You can (and should) just use simple attributes rather than do Java-style boilerplate getters and setters, because if you later do find a need for something simple attributes don't support you can refactor into a property without changing any of the calling code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.