下划线"_"在Python中的常见用途总结

2021-09-14  本文已影响0人  LabVIEW_Python

第一种用途:在循环中,不想给循环变量起名字,可以用"_",例如:

for _ in range(5):
    print(_)
0
1
2
3
4

第二种用途:在解包表达式中,对于不在乎(don't care)的变量,即可以忽略的元素,连存储其变量的名字都不想取,可以用"_",例如:

fruits = {'Yellow':['Banana','Mango'], 'Green':['Grapes','Guava'],'Red':['Apple','Cherry']}
_,_,red_fruits = fruits.values()
>>> red_fruits
['Apple','Cherry']
>>> _
['Grapes','Guava']

第三种用途:单个前导下划线,表示变量供内部使用,例如:

>>> class Fruits:
...   def __init__(self):
...     self.variety = 30
...     self._stock = "50 crates of each variety"
...   def _stage(self):
...     print("All fruits are fully ripe")
...
>>> check_fruits = Fruits()
>>> check_fruits.variety
30
>>> check_fruits._stock
'50 crates of each variety'
>>> check_fruits._stage()
All fruits are fully ripe
>>>

第四种用途:单个后导下划线,当必须使用已经被Python使用的关键字(keyword)时,为了避免命名冲突,可以加单个后导下划线,例如:class是关键字,用户可以使用class_
第五种用途:双前导下划线,解释器会自动在其名称前加入当前类名,以避免命名冲突,例如:

双前导下划线
第六种用途:双前后下划线的方法是 Python 中称为“魔术方法”或“dunder 方法”的特殊方法,当满足某些条件时,Python解释器会自动调用它们,例如:__ init __(),对象在创建时,Python解释器会自动调用init()方法。 魔术方法由Python解释器自动调用
上一篇 下一篇

猜你喜欢

热点阅读