通过装饰器使用setter RecursionError

时间:2017-06-26 17:30:00

标签: python python-decorators

我正在查看有关Python的一些链接 https://medium.com/the-renaissance-developer/python-101-object-oriented-programming-part-1-7d5d06833f26

还有一些装饰器用于创建(?)属性和一个setter方法。以下是代码:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    @property
    def number_of_wheels(self):
        return self.number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(self, number):
        self.number_of_wheels = number

这也是链接中的用法。

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print(tesla_model_s.number_of_wheels) # 2

所以,我试图理解为什么要使用它,而不是直接访问类变量本身。我尝试运行代码,但我得到了RecursionError

  File "C:/Users/Brandon/Desktop/Python/tryit.py", line 16, in number_of_wheels
    self.number_of_wheels = number
  [Previous line repeated 491 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object

最后我的问题是,这个代码怎么可能工作(它可能有什么问题?)更重要的是为什么我应该使用setter而不是直接访问类变量?

PS。欢迎使用任何指针,如读取链接或搜索关键字。

1 个答案:

答案 0 :(得分:2)

属性和属性不应该具有相同的名称,否则,setter和getter将一直反复调用自己。通常,您会在私有化(虽然它不是私有的)前面添加一个前导下划线,即为您创建属性的属性。

class Vehicle(object):
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self._number_of_wheels = number_of_wheels
        ...

    @property
    def number_of_wheels(self):
        return self._number_of_wheels

    @number_of_wheels.setter
    def number_of_wheels(self, number):
        self._number_of_wheels = number

还要记住在Python 2中继承object,以使您的课程与property一起使用。