美文网首页
Python 私有成员

Python 私有成员

作者: noteby | 来源:发表于2019-08-01 13:04 被阅读0次
    class Parent(object):
        def __init__(self,name,protected,private):
            self.name = name
            self._protected = protected  # _var: 保护成员
            self.__private = private # __var: 私有成员, 在类的外部无法直接访问
            
        def get_private(self):
            print('get private var from parent inner func: ', self.__private) # meth_1
            # print('get private var from inner func: ', self._Parent__private) # meth_2 
        def get_protect(self):
            print('get protect var from parent inner func: ', self._protected)
            
        def __private_func(self):
            print('this is parent private func')
    
    class Child(Parent):
        def get_private(self):
            print('get private var from child inner func: ', self.__private)
        def get_protect(self):
            print('get protect var from child inner func: ', self._protected)
        def get_private_func(self):
            # self.__private_func() # AttributeError
            self._Parent__private_func()
            
    parent = Parent(1,2,3)
    print(dir(parent))
    print(parent.name)
    print(parent._protected)
    print(parent._Parent__private)
    parent.get_protect()
    parent.get_private()
    # parent.__private_func() # AttributeError
    parent._Parent__private_func()
    
    
    child = Child(4,5,6)
    print(dir(child))
    print(child.name)
    print(child._protected)
    print(child._Parent__private)
    child.get_protect()
    # child.get_private() # AttributeError
    child.get_private_func()
    
    ['_Parent__private', '_Parent__private_func', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_protected', 'get_private', 'get_protect', 'name']
    1
    2
    3
    get protect var from parent inner func:  2
    get private var from parent inner func:  3
    this is parent private func
    ['_Parent__private', '_Parent__private_func', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_protected', 'get_private', 'get_private_func', 'get_protect', 'name']
    4
    5
    6
    get protect var from child inner func:  5
    this is parent private func
    

    相关文章

      网友评论

          本文标题:Python 私有成员

          本文链接:https://www.haomeiwen.com/subject/xieqdctx.html