Python版本为3.6.5.
。我正在学习如何正确使用我@decorator
的{{1}}语法糖。但似乎我做错了什么,我class Duck
因过热而死。这是演示:
qq_duck
终端:
class Duck(object):
def __init__(self, name):
self.name = name
@property
def name(self):
print("Quack! My name is", self.name)
@name.setter
def name(self, name):
print("I've decided to change my name into", name, ".")
print("So please call me", name, "from now on! Quack!")
self.name = name
请帮忙......
答案 0 :(得分:4)
当您指定self.name = name
时,setter函数会自行调用。这确实会导致无限递归。
修复可能是这样的:
class Duck(object):
def __init__(self, name):
self._name = name
@property
def name(self):
print("Quack! My name is", self._name)
# here you usually return the data member...
return self._name
@name.setter
def name(self, name):
print("I've decided to change my name into", name, ".")
print("So please call me", name, "from now on! Quack!")
self._name = name
注意成员self._name
与财产self.name
的不同之处。
答案 1 :(得分:1)
你的self.name所做的就是调用你刚才定义的属性。但这首先是它所称的,所以它会无限循环。
此代码可表示为:
self.name = "something" + ("something" + ("something" + ...[on to infinity!]...) )