私有属性

python 私有属性以两个下划线开头。

python 私有属性只能在类内部访问,类外面访问会出错。

python 私有属性之所以不能在外面直接通过名称来访问,其实质是因为 python 做了一次名称变换。

保护属性

python 保护属性更多的是一种语法上的标识,用来提醒直接修改改对象时候要小心。

python 保护属性和公开属性都可以在类外面直接访问。

class NewClass(object):
    def __init__(self):
        self.public_field = 5    # public
        self.__private_field = 10    # private
        self._protect_field = 99    # protect
    
    def __private_method(self):
        print "I am private method"
    
    def public_method(self):
        print "I am public method"

test = NewClass()

print test.public_field
test.public_method()

print test.__dict__    # {'_NewClass__private_field': 10, 'public_field': 5}

# 使用变换过后的名称访问,Success
print test._NewClass__private_field    # 10    
test._NewClass__private_method()    # I am private method 

# 直接访问,Fail
print test.__private_field    # AttributeError: 'NewClass' object has no attribute '__private_field'
test.__private_method()    # AttributeError: 'NewClass' object has no attribute '__private_method'
        

 

相关文章:

  • 2022-12-23
  • 2021-08-17
  • 2021-08-17
  • 2021-08-12
  • 2021-08-17
  • 2021-05-20
  • 2021-08-17
  • 2021-12-24
猜你喜欢
  • 2022-02-04
  • 2022-12-23
  • 2022-12-23
  • 2022-02-24
  • 2021-07-27
  • 2021-10-31
  • 2021-10-21
相关资源
相似解决方案