2、类的方法和属性的访问权限

2020-05-15  本文已影响0人  1e026ca57a8e

self.__foo = foo,双下划线为私有属性

# 类的方法和属性的访问权限
class Test:
    def __init__(self, foo):
        self.__foo = foo

    def __bar(self):
        print(self.__foo)
        print('__bar')


# __bar,__foo无法在外部访问
def main():
    test = Test('hello')
    test.__bar()  # AttributeError: 'Test' object has no attribute '__bar'
    print(test.__foo)   # AttributeError: 'Test' object has no attribute '__foo'


if __name__ == '__main__':
    main()
上一篇 下一篇

猜你喜欢

热点阅读