我是靠谱客的博主 幸福大碗,这篇文章主要介绍python---真假私有变量,现在分享给大家,希望可以做个参考。

定义私有属性或方法加个__即可(双下划线)

先来定义对象的私有属性(方法一样)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Person(): def __init__(self, name, age): self.name = name self.__age = age def __str__(self): return "{},{}".format(self.name, self.__age) if __name__ == '__main__': tom = Person("tom", 23) print(tom) # 访问私有属性就会报错 print(tom.age) print(tom.__age)

把这个对象的所有属性方法打印出来看看

复制代码
1
2
print(dir(tom))

在这里插入图片描述

这里会看到,我们的私有属性在底层被改了名字,所以用这个调用看看

复制代码
1
2
print(tom._Person__age)

在这里插入图片描述

所以就有结论了

Python中默认的成员函数,成员变量都是公开的(public),而且python中没有类似于java、C++的public,private等关键词来修饰成员函数,成员变量。

在python中定义私有变量只需要在变量名或函数名前加上 “__“两个下划线,那么这个函数或变量就会为私有的了。

在内部,python使用一种 name mangling 技术,将 __membername替换成 _classname__membername,所以你在外部使用原来的私有成员的名字时,会提示找不到。

命名混淆意在给出一个在类中定义“私有”实例变量和方法的简单途径, 避免派生类的实例变量定义产生问题,或者与外界代码中的变量搞混。 要注意的是混淆规则主要目的在于避免意外错误, 被认作为私有的变量仍然有可能被访问或修改。 在特定的场合它也是有用的,比如调试的时候, 这也是一直没有堵上这个漏洞的原因之一 (小漏洞:派生类和基类取相同的名字就可以使用基类的私有变量。)

正确的访问方式

属性装饰器 (有点类似与spring里的注解)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 属性访问器 @property def age(self): return self.__age print(tom.age) # 修改 @age.setter def age(self, age): self.__age = age print(tom.age) tom.age = 24 print(tom.age)

以上全部测试代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Person(): def __init__(self, name, age): self.name = name self.__age = age def __str__(self): return "{},{}".format(self.name, self.__age) # 属性访问器 @property def age(self): return self.__age @age.setter def age(self, age): self.__age = age if __name__ == '__main__': tom = Person("tom", 23) print(tom) # 访问私有属性就会报错 # print(tom.age) # print(tom.__age) # # 把这个对象的所有属性方法打印出来看看 # print(dir(tom)) # # print(tom._Person__age) print(tom.age) tom.age = 24 print(tom.age)

最后

以上就是幸福大碗最近收集整理的关于python---真假私有变量的全部内容,更多相关python---真假私有变量内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部