Python tricksUnderscores, Dunders, and More续篇

简介: Python tricksUnderscores, Dunders, and More续篇

Python tricks:Underscores, Dunders, and More
接上篇 https://developer.aliyun.com/article/1618427?spm=a2c6h.13148508.setting.17.77924f0edu1m2D

3. Double leading Underscore:“__var”
The naming patterns we’ve covered so far receive their meaning from agreed-upon convention only. With Python class attributes(variables and methods) that start with double underscores, things are a little different.

A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses.

This is also called name mangling - the interpreter changes the name of the variable in a way that makes it harder to create collisions when the class is extended later.

I know this sounds rather abstract. That’s why I put together this little code example we can use for experimentation:

>>> class Test:
...     def __init__(self):
...             self.foo = 11
...             self._bar = 23
...             self.__baz = 42

Let’s take a look at the attributes on this object using the built-in dir() function:

>>> t = Test()
>>> dir(t)
['_Test__baz', '__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__', '_bar', 'foo']

This gives us a list with the object’s attributes. Let’s take this list and look for our original variable names foo, _bar, and __baz. I promise you’ll notice some interesting changes.

First of all, the self.foo variable appears unmodified as foo in the attribute list.

Next up, self._bar behaves the same way–it shows up on the class as _bar. Like I said before, the leading underscore is just a convention in this case-a hint for the programmer.

However, with self.baz things look a little different. When you search for baz in that list, you’ll see that there is no variable with that name.

So what happened to __baz?

If you look closely, you’ll see there’s an attribute called Testbaz on this object. This is the name mangling that the Python interpreter applies. It does this to protect the variable from getting overridden in the subclasses.

Let’s create another class that extends the Test class and attempts to override its existing attributes added in the constructor:

>>> class ExtendedTest(Test):
...     def __init__(self):
...             super().__init__()
...             self.foo = 'overridden'
...             self._bar = 'overridden'
...             self.__baz = 'overridden'

Now, what do you think the values of foo, _bar, and__baz will be on instances of this ExtendedTest class?Let’s take a look:

>>> t2 = ExtendedTest()
>>> t2.foo
'overridden'
>>> t2._bar
'overridden'
>>> t2.__baz
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'ExtendedTest' object has no attribute '__baz'

Wait, why did we get that AttributeError when we tried to inspecdt the value of t2.baz?Name mangling strikes again! It turns out this object doesn’t even have a baz attribute:

>>> dir(t2)
['_ExtendedTest__baz', '_Test__baz', '__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__', '_bar', 'foo']

As you can see, baz got turned into _ExtendedTestbaz to prevent accidental modification. But the original _Test__baz is also still around:

>>> t2._ExtendedTest__baz
'overridden'
>>> t2._Test__baz
42

Double underscore name mangling is fulling transparent to the programmer. Take a look at the following example that will confirm this:

>>> class ManglingTest:
...     def __init__(self):
...             self.__mangled = 'hello'
...     def get_mangled(self):
...             return self.__mangled
... 
>>> ManglingTest().get_mangled()
'hello'
>>> ManglingTest().__mangled
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'ManglingTest' object has no attribute '__mangled'

Does name mangling also apply to method names? It sure does! Name mangling affects all names that with two underscore characters(“dunders”) in a class context:

>>> class MangledMethod:
...     def __method(self):
...             return 42
...     def call_it(self):
...             return self.__method()
>>> MangledMethod().__method()
Traceback (most recent call last):    
  File "<stdin>", line 1, in <module>
AttributeError: 'MangledMethod' object has no attribute '__method'
>>> MangledMethod().call_it()
42

Here’s another, perhaps surprising, example of name mangling in action:

_MangledGlobal__mangled = 23
>>> class MangledGlobal:
...     def test(self):
...             return __mangled
>>> MangledGlobal().test()
23

In this example, I declared _MangledGlobal mangled as a global variable. Then I accessedd the variable inside the context of a class named MangledGlobal. Because of name mangling, I was able to reference the_MangledGlobalmangled global variable as justmangled inside the test() method on the class.

The Python interpreter automatically expanded the name mangled to_MangledGlobalmangled because it begins with two underscore characters. This demonstrates that name mangling isn’t tied to class attributes specially. It applies to any name starting with two underscore characters that is used in a class context.

Whew! That was a lot to absorb.

To be honest with you, I didn’t write down these examples and explanations off the top my head. It took me some research and editing to do it. I’ve been using Python for years but rules and special cases like that aren’t constantly on my mind.

Sometimes the most important skills for a programmer are “pattern recognition” and knowing where to look things up. If you feel a little overwhelmed at this point, don’t worry. Take your time and play with some of the examples in this chapter.

Let these concepts sink in enough so that you’ll recognize the general idea of name mangling and some of the other behaviors I’ve shown you. If you encounter them “in the wild” one day, you’ll know what to look for in the documentation.

Sidebar: What are dunders?
If you’ve heard some experienced Pythonistas talk about Python or watched a few conference talks you may have heard the term dunder. If you’re wondering what that is, well, here’s your answer:

Double underscores are often referred to as “dunders” in the Python community. The reason is that double underscores appear quite often in Python code, and to avoid fatiguing their jaw muscles, Pythonistas often shorten “double underscore” to “dunder”.

For example, you’d pronounce baz as “dunder baz” . Likewise, init__ would be pronounced as “dunder init”, even though one might think it should be “dunder init dunder”.

4. Double Leading and Trailing Underscore: “var
Perhaps surprisingly, name mangling is not applied if a name starts and ends with double underscores. Variables surrounded by a double underscore prefix and postfix are left unscathed by the Python interpreter:

>>> class PrefixPostfixTest:
...     def __init__(self):
...             self.__bam__=42

>>> PrefixPostfixTest().__bam__
42

However, names that have both leading and trailing double underscores are reserved for special use in the language. This rule covers things like initfor object constructors, or call to make objects callable.

These dunder methods are often referred to as magic methods --but many people in the Python community, including myself, don’t like that word. It implies that the use of dunder methods is discouraged. Which is entirely not the case. They’re a core feature in Python and should be used as needed. There’s nothing “magical” or arcane(神秘的) about them.

However, as far as naming conventions go, it’s best to stay away from using names that start and end with double underscores in your own programs to avoid collisions with future changes to the Python language.

5. Single Underscore:“_”
Per convention, a single stand-alone underscore is sometimes used as a name to indicate that a variable is temporary or insignificant.

For example, in the following loop we don’t need access to the running index and we can use “_” to indicate that is just a temporary value:

>>> for _ in range(32):
...     print('Hello, World.')
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.

You can also use single underscores in unpacking expressions as a “don’t care” variable to ignore particular values. Again, this meaning is per convention only and it doesn’t trigger any special behaviors in the Python parser. The single underscore is simply a valid variable name that’s sometimes used for this purpose.

In the following code example, I’m unpacking a tuple into separate variable but I’m only interested in the values for the color and mileage fields. However, in order for the unpacking expression to succeed, I need to assign all values contained in the tuple to variables. That’s where “_” is useful as placeholder variable:

>>> car = ('red', 'auto', 12, 3812.4)
>>> color, _,_, mileage = car

>>> color
'red'
>>> mileage
3812.4
>>> _
12
Besides its use as a temporary variable, “_” is a special variable in most Python REPLs that represents the result of the last expression evaluated by the interpreter.

This is handy if you’re working in an interpreter session and you’d like to access the result of a previous calculation:

>>> 20 + 3
23
>>> _
23
>>> print(_)
23

It’s also handy if you’re constructing objects on the fly and want to interact with them without assigning them a name first:

>>> list()
[]
>>> _.append(1)
>>> _.append(2)
>>> _.append(3)
>>> _
[1, 2, 3]
相关文章
|
1月前
|
小程序 Linux Python
查找首字母与Python相关的的英文词汇小程序的续篇---进一步功能完善
查找首字母与Python相关的的英文词汇小程序的续篇---进一步功能完善
|
1月前
|
Java Python
Python tricksUnderscores, Dunders, and More
Python tricksUnderscores, Dunders, and More
|
4月前
|
SQL 数据库 Python
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
【Python】已完美解决:(executemany()方法字符串参数问题)more placeholders in sql than params available
73 1
|
4月前
|
Python
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
60 0
|
3天前
|
机器学习/深度学习 人工智能 TensorFlow
人工智能浪潮下的自我修养:从Python编程入门到深度学习实践
【10月更文挑战第39天】本文旨在为初学者提供一条清晰的道路,从Python基础语法的掌握到深度学习领域的探索。我们将通过简明扼要的语言和实际代码示例,引导读者逐步构建起对人工智能技术的理解和应用能力。文章不仅涵盖Python编程的基础,还将深入探讨深度学习的核心概念、工具和实战技巧,帮助读者在AI的浪潮中找到自己的位置。
|
3天前
|
机器学习/深度学习 数据挖掘 Python
Python编程入门——从零开始构建你的第一个程序
【10月更文挑战第39天】本文将带你走进Python的世界,通过简单易懂的语言和实际的代码示例,让你快速掌握Python的基础语法。无论你是编程新手还是想学习新语言的老手,这篇文章都能为你提供有价值的信息。我们将从变量、数据类型、控制结构等基本概念入手,逐步过渡到函数、模块等高级特性,最后通过一个综合示例来巩固所学知识。让我们一起开启Python编程之旅吧!
|
3天前
|
存储 Python
Python编程入门:打造你的第一个程序
【10月更文挑战第39天】在数字时代的浪潮中,掌握编程技能如同掌握了一门新时代的语言。本文将引导你步入Python编程的奇妙世界,从零基础出发,一步步构建你的第一个程序。我们将探索编程的基本概念,通过简单示例理解变量、数据类型和控制结构,最终实现一个简单的猜数字游戏。这不仅是一段代码的旅程,更是逻辑思维和问题解决能力的锻炼之旅。准备好了吗?让我们开始吧!
|
5天前
|
设计模式 算法 搜索推荐
Python编程中的设计模式:优雅解决复杂问题的钥匙####
本文将探讨Python编程中几种核心设计模式的应用实例与优势,不涉及具体代码示例,而是聚焦于每种模式背后的设计理念、适用场景及其如何促进代码的可维护性和扩展性。通过理解这些设计模式,开发者可以更加高效地构建软件系统,实现代码复用,提升项目质量。 ####
|
4天前
|
机器学习/深度学习 存储 算法
探索Python编程:从基础到高级应用
【10月更文挑战第38天】本文旨在引导读者从Python的基础知识出发,逐渐深入到高级编程概念。通过简明的语言和实际代码示例,我们将一起探索这门语言的魅力和潜力,理解它如何帮助解决现实问题,并启发我们思考编程在现代社会中的作用和意义。
|
5天前
|
机器学习/深度学习 数据挖掘 开发者
Python编程入门:理解基础语法与编写第一个程序
【10月更文挑战第37天】本文旨在为初学者提供Python编程的初步了解,通过简明的语言和直观的例子,引导读者掌握Python的基础语法,并完成一个简单的程序。我们将从变量、数据类型到控制结构,逐步展开讲解,确保即使是编程新手也能轻松跟上。文章末尾附有完整代码示例,供读者参考和实践。