[英]Property setter gives an error in Python
I am new to Python. 我是Python的新手。 I am try to learn the @property decorator in Python.
我尝试学习Python中的@property装饰器。 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". 在上面的代码中,第一个
print
给我“ 1”。 When I try to set the value to foo, it gives the below error: 当我尝试将值设置为foo时,出现以下错误:
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?
我的代码有什么问题?
A setter is used with the assignment operator =
: setter与赋值运算符
=
:
c.foo = 2
A further example how c.foo(2)
works: c.foo(2)
如何工作的另一个示例:
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. c.foo(…)
首先获取 c.foo
的值,然后调用该函数。
Did you mean to do 你是说要做
c.foo = 2
You use properties like you would attributes. 您可以像使用属性一样使用属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.