python中的protected和public变量有什么区别 [英] What is the difference between protected and public variable in python
问题描述
在python中,类中的protected和public变量有什么区别
In python, what is the difference between protected and public variable in a class
class A:
def __init__(self):
self._protected="protected"
self.__private="private"
self.public="public"
>>> a = A()
>>> a.public
'public'
>>> a._protected
'protected'
>>>
有人可以解释一下两者之间的区别,并指导我如何在python中使用受保护的变量吗 [如果我的方法使用率是假的话]
Can someone please explain me the difference, and guide me on how to use protected variable in python [In case my method is usage is false]
预先感谢.
推荐答案
除"public"外,这些术语均未包含.真的适用于Python.
None of those terms except "public" really apply in Python.
私人"广告仅适用于版本由于名称受到 __
的影响,但是仍然可以访问它.
The "private" version only "works" due to the mangling effect __
has on the name, but it's still possible to access it.
>>> a = A()
>>> print(a._A__private)
private
受保护"这里的保护"甚至更弱.您可以按照显示的方式正常访问它.仅根据约定,不应使用单个下划线前缀.单个下划线前缀在导入通配符时会产生一定的作用,,但我认为在属性名称中使用它不会产生任何效果.
"Protected" here is even weaker "protection". It can be accessed normally as you show. It's only by convention that a single underscore prefix shouldn't be used. A single underscore prefix has some effect when wildcard importing, but I don't believe it has any effect when used in an attribute name.
Python没有"private"类属性.可能有一些聪明的方法可以模仿它们,但是充其量只是hack.
Python does not have "private" class attributes. There may be some clever ways of emulating them, but they are hacks at best.
这篇关于python中的protected和public变量有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!