Python 混乱的二传手和接球手?为什么使用setter抛出';str';对象不可调用?
我听说使用getter和setter函数,如Python 混乱的二传手和接球手?为什么使用setter抛出';str';对象不可调用?,python,class,properties,setter,Python,Class,Properties,Setter,我听说使用getter和setter函数,如set\u value()和get\u value()不是Pythonic函数,最好使用带有setter和getter的属性对象 我运行了下面的代码,得到一个错误“str”对象不可调用“。当我搜索这个错误时,我发现了许多代码示例,其中类有一个属性和一个同名的方法(比如如果我在\uu init\uu方法中编写self.name而不是self.\uu name) 但是我在属性之前使用了两个下划线,所以这里不应该出现这种情况。看起来,当我试图调用name.s
set\u value()
和get\u value()
不是Pythonic函数,最好使用带有setter和getter的属性对象
我运行了下面的代码,得到一个错误“str”对象不可调用“
。当我搜索这个错误时,我发现了许多代码示例,其中类有一个属性和一个同名的方法(比如如果我在\uu init\uu
方法中编写self.name
而不是self.\uu name
)
但是我在属性之前使用了两个下划线,所以这里不应该出现这种情况。看起来,当我试图调用name.setter
时,我实际上调用了一个属性,并接收回存储在self.\uu name
中的字符串,然后我尝试调用其他内容
但是为什么呢?在所有setter示例中,它们与属性具有相同的名称,这不会导致问题。为什么它会在这里抛出错误,我该如何修复它
class Dog():
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, name_in):
self.__name = name_in
dog = Dog("Barbos")
print(dog.name) # this works
dog.name("Juchka") # and this throws an error:
# TypeError: 'str' object is not callable
你仍然在思考这里的方法。setter不是直接调用的。相反,当您为名称赋值时,会调用setter
使用分配:
dog.name = "Juchka"
Python将此转换为对setter方法的调用
仅访问dog.name
调用getter,getter方法返回一个字符串。调用是查找要应用调用的对象的单独表达式dog.name(“Juchka”)
首先执行dog.name
,并将(“Juchka”)
调用表达式应用于该属性查找的结果。属性查找返回了“Barbos”
,而“Barbos”(“Juchka”)
确实不起作用
演示:
>>狗=狗(“芭比”)
>>>狗的名字
“巴博斯”
>>>“Barbos”(“Juchka”)#当你试着叫狗的时候会发生什么事。名字(…)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“str”对象不可调用
>>>dog.name=“Juchka”
>>>狗的名字
“朱奇卡”
Setter的用法类似于:dog.name=“Juchka”
Setter是用来挂接分配的。您将使用dog.name=“Juchka”
。您将setter用作dog.name='newname'
。
>>> dog = Dog("Barbos")
>>> dog.name
'Barbos'
>>> 'Barbos'("Juchka") # what really happens when you try to call dog.name(...)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> dog.name = "Juchka"
>>> dog.name
'Juchka'