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
。您的属性名为getCity
和getCountry
,所以不要使用:
a2.setCity("Athens")
a2.setCountry("Greece")
:
a2.getCity = "Athens"
a2.getCountry = "Greece"
如果您想将getCity
和setCity
作为普通方法调用,而不是将getCity
作为其setter为setCity
的属性,只需删除@property
装饰符。