我是Python的新手,我刚刚在编程教科书中找到了OOP章节。
教科书没有解释property()
的工作原理。
property()
如何知道将名称更改为new_name
而不是new_name + "lololol"
?
我创建了set_name2
因为我想了解property()
的工作原理。但令我惊讶的是,这个名字没有改为new_name + "lololol"
。
# Property Critter
class Critter(object):
"""A virtual pet"""
def __init__(self, name):
print "A new critter has been born!"
self.__name = name
def get_name(self):
return self.__name
def set_name(self, new_name):
if new_name == "":
print "A critter's name can't be an empty string."
else:
self.__name = new_name
print "Name change successful."
def set_name2(self, new_name):
self.__name = new_name + "lololol"
print "Name change successful (set_name2!)"
name = property(get_name, set_name, set_name2)
def talk(self):
print "\nHi, I'm", self.name
# main
crit = Critter("Poochie")
crit.talk()
print "\nMy critter's name is:",
print crit.name
print "\nAttempting to change my critter's name."
crit.name = ""
print "\nAttempting to change my critter's name again."
crit.name = "Randolph"
crit.talk()
raw_input("\n\nPress enter to exit.")
答案 0 :(得分:2)
property
的第三个参数应该是删除属性的函数,而不是另一个setter函数(函数的名称没有特殊含义,只是命名它{{ 1}}并不能使它成为一个设定者。 official documentation of property很好地解释了set_something
,fget
和fset
预期会做什么。
要了解 fdel
如何在内部运作,您可以阅读Ashwini Chaudhary指出的descriptors。
以下是对代码的一些修改,以说明property
行为:
property
哪个输出:
# Property Critter
class Critter(object):
"""A virtual pet"""
def __init__(self, name):
print "A new critter has been born!"
self.__name = name
def get_name(self):
return self.__name
def set_name(self, new_name):
if new_name == "":
print "A critter's name can't be an empty string."
else:
self.__name = new_name
print "Name change successful."
def del_name(self):
self.__name = "Scratchy"
print "If you don't give me a name, I will choose one myself!"
name = property(get_name, set_name, del_name)
def talk(self):
print "\nHi, I'm", self.name
# main
crit = Critter("Poochie")
crit.talk()
print "\nMy critter's name is:",
print crit.name
crit.name = ""
crit.name = "Itchy"
crit.talk()
del crit.name
crit.talk()