0
我正在查看一些关于Python的链接。
https://medium.com/the-renaissance-developer/python-101-object-oriented-programming-part-1-7d5d06833f26在装饰器中使用setter RecursionError
还有在那里用于创建(?)属性和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
最后我的问题是,如何能此代码的工作(有什么错呢,也许?),更重要的,为什么我应该使用二传手不是直接访问类的变量?
ps。任何指向链接的阅读或关键字搜索都欢迎。