在Python中可以通过在属性变量名前加上双下划线定义属性为私有属性,如例子:
#! encoding=UTF-8 class A: def __init__(self): # 定义私有属性 self.__name = "wangwu" # 普通属性定义 self.age = 19 a = A() # 正常输出 print a.age # 提示找不到属性 print a.__name
Traceback (most recent call last): File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in <module> print a.__name AttributeError: A instance has no attribute '__name'
#! encoding=UTF-8 class A: def __init__(self): # 定义私有属性 self.__name = "wangwu" # 普通属性定义 self.age = 19 a = A() a.__name = "lisi" print a.__name
#! encoding=UTF-8 class A: def __init__(self): # 定义私有属性 self.__name = "wangwu" # 普通属性定义 self.age = 19 class B(A): def sayName(self): print self.__name b = B() b.sayName()
Traceback (most recent call last): File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 19, in <module> b.sayName() File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in sayName print self.__name AttributeError: B instance has no attribute '_B__name'
#! encoding=UTF-8 class A: def say(self): print self.name print self.__age class B(A): def __init__(self): self.name = "wangwu" self.__age = 20 b = B() b.say()
wangwu Traceback (most recent call last): File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 15, in <module> b.say() File "C:\Users\lee\Documents\Aptana Studio 3 Workspace\testa\a.py", line 6, in say print self.__age AttributeError: B instance has no attribute '_A__age'