如何在Python构造函数中使用二传器



python gurus,我得到了完成的任务要完成,我最终写了编写代码,但是我一直遇到此错误 "Oops! Don't forget to use the setters in your constructor, and print "<attribute name> changed" whenever a setter is called (regardless of whether the correct type was supplied)"我的代码有一个构造函数和六个方法。前三种方法是Getters,而最后三个是设定器。我的问题是如何解决此错误Oops! Don't forget to use the setters in your constructor, and print "<attribute name> changed" whenever a setter is called (regardless of whether the correct type was supplied),因为似乎已经在使用设定器,但不知道为什么此错误持续感谢。这是我的完整代码:

class TodoItem:
    def __init__(self, title, description, completed=False):
        self.title = title
        self.description = description
        self.completed = completed
    def getTitle(self):     
        print ("title accessed")
        return self.title
    def getDescription(self):      
        print ("description accessed")
        return self.description
    def getCompleted(self):       
        print ("completed accessed")
        return self.completed
    def setTitle(self, newtitle):
        print ("title changed")
        if type(newtitle) == str:
            self.title = newtitle
        else:
            print ("invalid value title changed")
            self.title = None
    def setDescription(self, newdescription):
        print ("description changed")
        if type(newdescription) == str:
            self.description = newdescription
        else:
            print ("invalid value description changed")
            self.description = None
    def setCompleted(self, newbool):
        print ("completed changed")
        if type(newbool) == bool:
            self.completed = newbool
        else:
            print ("invalid value completed changed")
            self.completed = None

这是我测试上述代码的代码:

mytodo = TodoItem(99,"make a list and go to the store")
mytodo.setTitle(99)
print (mytodo.getTitle())

通常在python中我们不使用getter and setter,无论如何,如果您真的需要它们,则有两种好方法可以做到这一点(用Var1和var2说明):

class Example(object):
    def __init__(self, var1, var2):
        self.__var1 = var1
        self.__var2 = var2
    @property
    def var1(self):
        return self.__var1
    @var1.setter
    def var1(self, value):
        self.__var1 = value
    def get_var2(self):
        return self.__var2
    def set_var2(self, value):
        self.__var2 = value
    var2 = property(get_var2, set_var2)
if __name__ == "__main__":
    # With those implementations you can call the getter and setter as if
    # you directly call and modify the variable (which is what we want in
    # python).
    e = Example()
    e.var1 = 1 # will call the method with the @var1.setter decorator
    print(e.var1) # will call the method with the @property decorator
    e.var2 = 1 # will call the method set_var2()
    print(e.var2) # will call the method get_var2()

另外,在python中指出变量是私有的,我们在它们之前添加" __"," _"表示受保护。

最新更新