#测试python中的name mangle机制
class A:
__attr1=1 #私有 类属性
def __init__(self):
self.attr2=2 #私有 对象属性
@classmethod
def getAttr1(cls): #定义类方法使用修饰器,并且传入类对象cls
return cls.__attr1
def getAttr2(self):
return self.__attr2
python中不存在私有变量,即类外可以访问到类内定义的私有变量。
name mangle,即名称修饰,是python对私有变量采用的一种修饰机制。
python中没有访问控制符,如public,private等,在希望表示私有属性或私有方法时,使用两个下划线做前缀,python解释器会将该属性或者方法偷偷将其命名为“_类名__属性名/方法名”。
注意虽然类属性__attr1被定义为私有属性,但是我们仍然可以在类外访问其值:
print(A._A__attr1) #!注意此处类属性可通过类名或对象访问
#结果
1
{'__module__': '__main__', '_A__attr1': 1, '__init__':
<function A.__init__ at 0x7f01907cd048>,
'getAttr1': <classmethod object at 0x7f0191b570f0>,
'getAttr2': <function A.getAttr2 at 0x7f01907cd6a8>,
'__dict__': <attribute '__dict__' of 'A' objects>,
'__weakref__': <attribute '__weakref__' of 'A' objects>,
'__doc__': None}
总结:
python中的私有是假私有!