类型错误:"str"对象在我更改实例属性时不可调用


class Airport:
def __init__(self, code, city, country):
self._code=code
self._city=city
self._country=country
def __repr__(self):
return "%s(%s,%s)"%(self._code, self._city, self._country)
def getCode(self):
return self._code
@property
def getCity(self):
print('property')
return self._city
@property
def getCountry(self):
return self._country
@getCity.setter
def setCity(self,city):
print('changecity')
self._city=city
@getCountry.setter
def setCountry(self,country):
self._country=country
a1 = Airport("YXU", "London", "Canada")
a2 = Airport("ABC", "Madrid", "Spain")
a2.setCity("Athens")
a2.setCountry("Greece")

line 26 (a2.setCity("Athens")),我面临这个错误:

TypeError: 'str' object is not callable

为什么是错的?我没有调用任何字符串作为函数,也没有使用str作为变量名。功能getCity正常,但setCity有问题。a2本身是一个对象,而不是str

设置相关属性时调用@setter。您的属性名为getCitygetCountry,所以不要使用:

a2.setCity("Athens")
a2.setCountry("Greece")

:

a2.getCity = "Athens"
a2.getCountry = "Greece"

如果您想将getCitysetCity作为普通方法调用,而不是将getCity作为其setter为setCity的属性,只需删除@property装饰符。

最新更新