封装之如何隐藏属性

佐手、 提交于 2019-11-27 02:58:59
class A:    __x = 1     #   _A__x = 1    def __init__(self,name):        self.__name=name       # self._A__name = name    def __foo(self):            # _A__foo        print('run foo')# print(A.__dict__)'''{'__module__': '__main__', '_A__x': 1, '__init__': <function A.__init__ at 0x0000017B28A1F950>, '_A__foo': <function A.__foo at 0x0000017B28A1F488>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}''''''这种变形的特点:    1、外部无法直接使用:obj.__AttrName    2、在类内部是可以直接使用:obj.__AttrName    3、子类无法覆盖父类__开头的属性'''class A:    def foo(self):        print('A foo')    def bar(self):        print('A bar')        self.foo()class B(A):    def foo(self):        print('b foo')b1 = B()b1.bar()# 结果# A bar# b fooclass A:    def __foo(self):        print('A foo')    def bar(self):        print('A bar')        self.__foo()class B(A):    def __foo(self):        print('b foo')b1 = B()b1.bar()# 结果# A bar# A foo
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!