Reputation: 3383
I am new to Python. I am try to learn the @property decorator in Python. Here is my code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class C(object):
"""docstring for C"""
def __init__(self, foo):
self._foo = foo
@property
def foo(self):
return self._foo
@foo.setter
def foo(self, value):
self._foo = value
return self.foo
c = C(1)
print c.foo
print c.foo(2)
In the above code first print
gave me "1". When I try to set the value to foo, it gives the below error:
Traceback (most recent call last):
File "sub.py", line 23, in <module>
print c.foo(2)
TypeError: 'int' object is not callable
How to solve this error. What's wrong my code?
Upvotes: 0
Views: 1670
Reputation: 26022
A setter is used with the assignment operator =
:
c.foo = 2
A further example how c.foo(2)
works:
In [7]: c = C(lambda x: x*x)
In [8]: c.foo(2)
Out[8]: 4
c.foo(…)
first gets the value in c.foo
, then invokes the function.
Upvotes: 5
Reputation: 83255
Did you mean to do
c.foo = 2
You use properties like you would attributes.
Upvotes: 4