【发布时间】:2019-01-15 06:45:09
【问题描述】:
-
在 __init__ 中使用 self.cost = cost,我们得到以下输出
在__init__
里面内部设置器
内部属性
100
-
在 __init__ 中使用 self._cost = cost,我们得到以下输出
在__init__
里面内部属性
100
在第一点,内部 setter 被调用,但不是在点 2。
class Book(object): def __init__(self,cost): print('inside __init__') self.cost = cost #self._cost = cost @property def cost(self): print('inside property') return self._cost @cost.setter def cost(self,value): print('inside setter') self._cost = value book = Book(100) print(book.cost)
【问题讨论】:
-
是的,因为当您使用属性
.some_name时,会激活一个名为some_name的属性。请注意,some_name与_some_name不同。单个下划线没有什么特别之处,它就像任何其他有效的 Python 标识符一样。在 Python 中,只有隐私约定,如果您想继续玩“私有”_some_name,该语言不会阻止您。
标签: python