Python Getter Setter
- @property 表示只读
- @xxx.setter 表示可写
- 属性命名规则
- 属性不能和方法名同名
- 1 个下划线会被外部覆盖,所以属性不能以 1个下划线开头
- 外部调用 self._xxx = 1 会覆盖类内部调用的 self._xxx
- 2 个下划线不会被外部覆盖,所以属性应以 2 个下划线开头
- 外部调用 self.__xxx = 1 不会覆盖类内部调用的 self.__xxx
- 这样外部的 self.__xxx 和内部的 self.__xxx 是不同的值
class Person:
def __init__(self, hello):
self.__hello = hello
@property
def hello(self):
return self.__hello
@hello.setter
def hello(self, hello):
self.__hello = hello