保护变量、私有变量、私有方法介绍:
_xxx: 单下划线开头叫保护变量,意思是只有类对象和子类对象自己能访问到这些变量,此变量不能通过from XXX import xxx 导入;
__xxx : 双下划线开头叫私有成员,只允许类本身访问,连子类对象也不能访问到这个数据。
__xxx__ : 前后均有一个“双下划线”,系统定义名字, 代表python里特殊方法专用的标识,如 __init__()代表类的构造函数。 代码示例:
class Pub(object):
#定义类的正常变量、保护变量、私有变量
var1 = 'Hello'
_var2 = 'yes'
__var3 = 'haha' #代表类的构造函数
def __init__(self):
self._a = 123
self.__b = 456
self.c = 789 def show_a_var(self):
return self._a def show_b_var(self):
return self.__b def show_var2(self):
return self._var2 def show_var3(self):
return self.__var3 #定义私有方法
def __privatemethod(self):
print('这是私有方法') class Foo(Pub):
pass # 类的实例化对象
sl = Pub() #第一:访问正常变量
print(sl.c) #
print(sl.var1) #第二:访问保护变量
print(sl._a) #
print(sl._var2) #yes #第三:访问私有变量:实例._类名__变量名
print(sl._Pub__var3) # haha
print(sl._Pub__b) #
# print(sl.__b) #错误的写法 #第四:访问正常类方法
print(sl.show_a_var()) #
print(sl.show_b_var()) #456 间接去访问,得到self.__b
print(sl.show_var2()) #yes
print(sl.show_var3()) #haha 间接去访问,得到self.__var3 #第五:访问私有方法: 实例._类名__方法名()
sl._Pub__privatemethod() #结果:这是私有方法 #子类的实例化对象
s2=Foo()
print(s2.show_a_var()) #
print(s2.show_b_var()) #
print(s2.show_var2()) #ye3
print(s2.show_var3()) #haha
私有变量、私有方法应用:
class people():
__place = "nanjing"
_age1 = 20 def __init__(self, name):
self.name = name def __sayhello(self):
print("%s say hello" % self.name) class teacher(people):
pass t1 = teacher("cmz")
print(t1._people__place) # 访问私有变量
t1._people__sayhello() # 访问私有方法 结果是
nanjing
cmz say hello python私有属性和方法案例
单下划线应用:
class people():
__place = "nanjing"
_age = 20 def __init__(self, name):
self.name = name def _test(self):
print("from people test") def __sayhello(self):
print("%s say hello" % self.name) class teacher(people):
pass print(people.__dict__) #<class '__main__.people'> t1 = teacher("cmz")
print(t1) #<__main__.teacher object at 0x029026F0> #得到年龄2中方式
#方式一
print(t1._age) #
#方式二
# print(people._age) #调用test函数2中方式
#方式一
t1._test()
#方式二
people._test(t1) #调用私有方法
t1._people__sayhello() #cmz say hello '''结果
{'__module__': '__main__', '_people__place': 'nanjing', '_age': 20, '__init__': <function people.__init__ at 0x0081B5D0>, '_test': <function people._test at 0x0081B4F8>, '_people__sayhello': <function people.__sayhello at 0x050674F8>, '__dict__': <attribute '__dict__' of 'people' objects>, '__weakref__': <attribute '__weakref__' of 'people' objects>, '__doc__': None}
<__main__.teacher object at 0x00359390>
20
from people test
from people test
cmz say hello '''
双下划线应用:
class people():
__place = "nanjing"
_age = 20 def __init__(self, name):
self.name = name def __sayhello(self):
print("%s say hello" % self.name) class teacher(people):
pass t1 = teacher("cmz")
print(t1._people__place)
t1._people__sayhello() 结果是
nanjing
cmz say hello