Day2面向对象进阶
访问可见性问题 在Python中,属性和方法的访问权限只有两种,也就是公开的和私有的,如果希望属性是私有的,在给属性命名时可以用两个下划线作为开头,下面的代码可以验证这一点。 # 私有变量,变量名前面加"__" # 如果非要使用私有变量,那么可以使用dir(class())去查看它真正的名字. # 私有变量/函数,在类内部可以直接调用. # 如果你想体现一个变量/函数特别重要你可以使用"_" class Test: def __init__(self, foo): self.__foo = foo def __bar(self): print(self.__foo) print('__bar') def main(): test = Test('hello') # AttributeError: 'Test' object has no attribute '__bar' test.__bar() # AttributeError: 'Test' object has no attribute '__foo' print(test.__foo) if __name__ == "__main__": main() @property装饰器 使用装饰器的时候,需要注意: 1. 装饰器名,函数名需要一致. 2. property需要先声明,再写setter,顺序不能倒过来 3.