类私有变量命名

带有两个下划线开头的函数是声明该属性为私有,不能在类地外部被使用或直接访问。

原因是在外部访问时Python应用了另一个变量名。
如下代码,__sex声明该变量是类的私有变量,不能直接用类如. __spam访问,而是. _classname__spam(Python把这种技术叫做“name mangling”)

class Students:
def init(self,sex,name,age,scores):
self.__sex = sex
self.age = age
self.name =name
self.scores = scores
def get_data(self):
return self.name,self.age,self.scores,self.__sex

stu = Students(‘男’,‘taon’,‘23’,‘90’)
print(stu.__sex,stu.dict)
print(stu._Students__sex,stu.dict)

前者报错
AttributeError: ‘Students’ object has no attribute ‘__sex’

后者输出为
男 {‘name’: ‘tao’, ‘_Students__sex’: ‘男’, ‘age’: ‘23’, ‘scores’: ‘90’}

猜你喜欢

转载自blog.csdn.net/m0_50799972/article/details/114236388
今日推荐