Python 双下划线前缀在变量中有什么作用
当双下划线被添加为Python变量的前缀时,名称修饰过程将应用于指定的标识符(__var
)
为了避免与子类命名冲突,名称修饰包括重写属性名。
示例
以下是解释Python中双下划线的程序示例−
class Python:
def __init__(self):
self.car = 5
self._buzz = 9
self.__fee = 2
d = Python()
print(dir(d))
输出
以下是上述代码的输出结果 –
['_Python__fee', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_buzz', 'car']
理解上述代码
- 上述代码中,比较了单下划线、双下划线和普通元素,且通过在代码中添加一个类。
-
这里,基本关键字”car”、”buzz”和”fee”被用作占位符,根据输入条件或程序接收到的新数据而改变。
-
通过dir()函数提供了一个由作为参数传递给函数的对象的有效属性列表。
上述代码中,”car”和”_buzz
“变量似乎没有受到影响,但”__fee
“变量已经被改为”_Python__fee
“。为了防止该变量在子类中被覆盖,对其进行了名称混淆。
Python中的双下划线(__
)前缀变量
在Python中,私有变量使用双下划线作为前缀进行定义。有时这也被称为”dunder”。这些名称强制将其所指的变量的作用域限制在本地。当变量在函数中以双下划线声明时,Python会对其名称进行混淆,以便它不能超出作用域。
示例
以下是Python中使用双下划线前缀变量的示例。
我们将创建一个名为Python的类作为示例。我们将添加一个可通过函数设置的属性”__name
“到这个类中。此外,我们将创建一种让函数可以访问”__name
“属性的方式。
class Sports:
def __init__(self, players):
self.players = players
def names(self, names):
self.__names = names
def GetName(self):
return self.__names
Cricket = Sports(12)
Cricket.names("Sachin Tendulkar")
print(Cricket.GetName())
print(Cricket.players)
print(Cricket.__names)
输出
当我们从类内部访问Cricket Sports时,上述代码为其命名并写出名称。从下面的输出中可以看出,虽然我们可以直接访问players,但无法直接访问names。
Sachin Tendulkar12
Traceback (most recent call last):
File "main.py", line 12, in <module>
print(Cricket.__names)AttributeError: 'Sports' object has no attribute '__names'
示例
为了演示如何覆盖函数,让我们创建一个继承自 Coding 类的新类。
class PythonClass():
def __init__(self):
super().__init__()
self.d = "overriding"
self._e = "overriding"
self.__f = "overriding"
object2 = PythonClass()
print(object2.d)
print(object2._e)
print(object2.__f)
输出
下面是以上代码的输出结果:
overriding
overriding
Traceback (most recent call last):
File "main.py", line 12, in
print(object2.__f)AttributeError: 'PythonClass' object has no attribute '__f'
名称压缩再次起作用。对象2.f被更改为_PythonClass__f
。现在,使用修改后的属性将该元素放入打印。
print(object2._PythonClass__f)
现在,输出如下:
overriding
overriding
overriding
示例
以下示例确定该类的方法可用于访问Double Pre Underscore变量。
class Python:
def __init__(self):
self.__datacamp = "Programming"
def get_datacamp(self):
return self.__datacamp
object = Python()
# Printing the "Programming" that is a __var
print(object.get_datacamp())
# An error occurs here. The name of the variable is changed
print(object.__datacamp)
输出
以下是上述代码的输出:
Programming
Traceback (most recent call last):
File "main.py", line 11, in <module>
print(object.__datacamp)
AttributeError: 'Python' object has no attribute '__datacamp'
示例
另外,对于方法名称,您可以使用双下划线。
class Python:
def __getdatacamp(self):
return "Programming"
def calling_datacamp(self):
return self.__getdatacamp()
object = Python()
# Returning the double underscore prefix method
print(object.calling_datacamp())
# An error occurs here
print(object.__getdatacamp())
输出
以下是以上代码的输出 –
Programming
Traceback (most recent call last):
File "main.py", line 11, in
print(object.__getdatacamp())
AttributeError: 'Python' object has no attribute '__getdatacamp'
示例
让我们再次看一下名称混淆。我们首先创建一个变量叫做Python,然后尝试使用双下划线名称访问它。
_Python__name = "Programming"
class Python:
def return_name(self):
return __name
object = Python()
# The __name variable gets printed
print(object.return_name())
输出
以下是上述代码的输出 –
Programming