python类的私有属性和公共属性

对于python而言,类的属性的可见度只有两种,public和private。

类的私有属性便是在前面加上“__”标识符,而公共属性则不必。

在类的外面访问私有属性会引发异常。

class Base:
    def __init__(self, value):
        self.__value = value

b = Base(5)
print(assert b.__value)

Traceback (most recent call last):
  File "/Users/yangjiajia/Desktop/project/python/algebra/test.py", line 19, in <module>
    print(b.__value)
AttributeError: 'Base' object has no attribute '__value'

属性被私有化,即使继承他的字类也不能访问到。

class Parent:
    def __init__(self, value):
        self.__value = value


class Child(Parent):
    def get_value(self):
        return self.__value

child = Child(4)
print(child.get_value())

Traceback (most recent call last):
  File "/Users/yangjiajia/Desktop/project/python/algebra/test.py", line 24, in <module>
    print(child.get_value())
  File "/Users/yangjiajia/Desktop/project/python/algebra/test.py", line 21, in get_value
    return self.__value
AttributeError: 'Child' object has no attribute '_Child__value'

为何会这样?因为python会对类的私有属性做些转换,以保证private字段的私密性。当编译器看到Child.get_value方法要访问私有属性时,他会先把__value变换为_Child_value然后再进行访问,但实际上该私有属性是_Parent__value。字类无法访问父类的私有属性,只是因为访问的名称不同。

查询该对象的属性字典便知

class Parent:
    def __init__(self, value):
        self.__value = value


class Child(Parent):
    def name(self):
        names = 'yang'

    def get_value(self):
        return self.__value

child = Child(4)
print(child.__dict__)

{'_Parent__value': 4}

python开发的原则还是要少用私有属性,如果需要保证属性不重复,可以在其前面加上单个下划线。

class Parent:
    def __init__(self, value):
        self._value = value


class Child(Parent):
    def get_value(self):
        return self._value

child = Child(4)
assert child._value == 4

猜你喜欢

转载自blog.csdn.net/yangjiajia123456/article/details/80383475