In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the hidden rules of underlining in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the hidden rules of underlining in Python.
1. Single leading underscore _ var
When it comes to variable and method names, a single underscore prefix has a conventional meaning. It is a hint for programmers: it means that the Python community agrees on what it should mean, but the behavior of the program is not affected.
The underscore prefix means to tell other programmers that variables or methods that begin with a single underscore are for internal use only. This convention is defined in PEP 8.
This is not mandatory by Python. Python does not have the strong distinction between "private" and "public" variables like Java. It's like someone put forward a little underlined warning sign and said:
"Hey, it's not really part of the public interface of the class. Just leave it alone."
Look at the following example:
Class Test: def _ _ init__ (self): self.foo = 11 self._bar = 23
What happens if you instantiate this class and try to access the foo and _ bar properties defined in the _ _ init__ constructor? Let's take a look:
> t = Test () > t.foo 11 > t._bar 23
You will see that a single underscore in _ bar does not prevent us from "entering" the class and accessing the value of the variable.
This is because a single underscore prefix in Python is just a convention-at least relative to variable and method names.
However, leading underscores do affect how names are imported from the module.
Suppose you have the following code in a module called my_module:
# This is my_module.py: def external_func (): return 23 def _ internal_func (): return 42
Now, if you import all names from a module using wildcards, Python will not import names with leading underscores (unless the module defines a _ _ all__ list that overrides this behavior):
> from my_module import * > > external_func () 23 > _ internal_func () NameError: "name'_ internal_func' is not defined"
By the way, wildcard imports should be avoided because they make it unclear what names exist in the namespace. For the sake of clarity, it is better to stick to regular import.
Unlike wildcard imports, regular imports are not affected by leading individual underscore naming conventions:
> import my_module > my_module.external_func () 23 > my_module._internal_func () 42
I know this may be a little confusing. If you follow PEP 8 recommendations to avoid wildcard imports, that's all you really need to remember:
A single underscore is an Python naming convention that indicates that the name is for internal use. It is usually not enforced by the Python interpreter, but only as a hint to the programmer.
two。 Single end underlined var_
Sometimes, the most appropriate name of a variable is already occupied by a keyword. Therefore, names such as class or def cannot be used as variable names in Python. In this case, you can attach an underscore to resolve the naming conflict:
> def make_object (name, class): SyntaxError: "invalid syntax" > def make_object (name, class_):. Pass
In summary, a single underscore (suffix) is a convention to avoid naming conflicts with the Python keyword. PEP 8 explains this convention.
3. Double leading underscore _ _ var
So far, the meaning of all the naming patterns we have covered comes from agreed conventions. For the properties (including variables and methods) of the Python class that starts with a double underscore, the situation is a little different.
The double underscore prefix causes the Python interpreter to override property names to avoid naming conflicts in subclasses.
This is also called name modification (name mangling)-the interpreter changes the name of the variable so that conflicts do not occur when the class is extended.
I know it sounds abstract. So, I combined a small code example to illustrate:
Class Test: def _ init__ (self): self.foo = 11 self._bar = 23 self.__baz = 23
Let's look at the properties of this object with the built-in dir () function:
> t = Test () > > dir (t) ['_ Test__baz','_ class__','_ _ delattr__','_ _ dict__','_ _ dir__','_ _ doc__','_ eq__','_ format__','_ ge__','_ getattribute__','_ gt__','_ _ hash__','_ _ init__' '_ _ le__',' _ _ lt__','_ _ module__','_ _ ne__','_ _ new__','_ _ reduce__','_ _ reduce_ex__','_ _ repr__','_ _ setattr__','_ _ sizeof__','_ str__','_ subclasshook__','_ weakref__','_ bar', 'foo']
The above is a list of the properties of this object. Let's take a look at this list and look for our original variable names foo,_bar and _ _ baz. I'm sure you'll notice some interesting changes.
The self.foo variable appears as unmodified to foo in the property list.
Self._bar behaves the same way-it appears on the class in the form of _ bar. As I said before, in this case, leading underlining is just an agreement. Just give the programmer a hint.
For self.__baz, however, the situation looks a little different. When you search the list for _ _ baz, you won't see a variable with that name.
_ _ baz, what happened?
If you look closely, you will see that there is a property called _ Test__baz on this object. This is the name modification done by the Python interpreter. It does this to prevent variables from being overridden in subclasses.
Let's create another class that extends the Test class and try to override the existing properties added in the constructor:
Class ExtendedTest (Test): def _ _ init__ (self): super (). _ _ init__ () self.foo = 'overridden' self._bar =' overridden' self.__baz = 'overridden'
Now, do you think the values of foo,_bar and _ _ baz will appear on the instance of this ExtendedTest class? Let's take a look:
> T2 = ExtendedTest () > t2.foo 'overridden' > t2._bar' overridden' > t2.__baz AttributeError: "'ExtendedTest' object has no attribute' _ _ baz'"
Wait a minute, why do we get AttributeError when we try to look at the value of T2. _ _ baz? The name modifier has been triggered again! As 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__' '_ _ le__',' _ _ lt__','_ _ module__','_ _ ne__','_ _ new__','_ _ reduce__','_ _ reduce_ex__','_ _ repr__','_ _ setattr__','_ _ sizeof__','_ str__','_ subclasshook__','_ weakref__','_ bar', 'foo' 'get_vars']
As you can see, _ _ baz becomes _ ExtendedTest__baz to prevent accidental modification:
> > t2._ExtendedTest__baz 'overridden'
But the original _ Test__baz is still there:
> t2._Test__baz 42
Double underscore name decorations are completely transparent to programmers. The following example confirms this:
Class ManglingTest: def _ init__ (self): self.__mangled = 'hello' def get_mangled (self): return self.__mangled > ManglingTest (). Get_mangled ()' hello' > ManglingTest (). _ _ mangled AttributeError: "'ManglingTest' object has no attribute' _ mangled'"
Does the name modifier also apply to method names? Yes, it also applies. Name decorations affect all names that begin with two underscore characters ("dunders") in the context of a class:
Class MangledMethod: def _ method (self): return 42 def call_it (self): return self.__method () > > MangledMethod (). _ method () AttributeError: "'MangledMethod' object has no attribute' _ method'" > MangledMethod (). Call_it () 42
This is another perhaps surprising example of the use of name modification:
_ MangledGlobal__mangled = 23 class MangledGlobal: def test (self): return _ _ mangled > MangledGlobal () .test () 23
In this example, I declare a global variable named _ MangledGlobal__mangled. Then I access the variable in the context of a class named MangledGlobal. Because of the name modification, I was able to reference the _ MangledGlobal__mangled global variable with _ _ mangled within the test () method of the class.
The Python interpreter automatically extends the name _ _ mangled to _ MangledGlobal__mangled because it begins with two underscore characters. This indicates that the name modifier is not specifically associated with class properties. It applies to any name that begins with two underscore characters used in the context of a class.
There's a lot to absorb.
To be honest, these examples and explanations didn't pop out of my head. I did some research and processing to get it out. I've been using Python for many years, but rules and special situations like this don't always come to mind.
Sometimes the most important skill for programmers is "pattern recognition" and knows where to look for information. If you feel a little overwhelmed at this point, please don't worry. Take your time and try some of the examples in this article.
Immerse these concepts completely so that you can understand the general idea of name modification, as well as some of the other behaviors I've shown you. If you run into them one day, you will know what to look up in the document.
4. Double leading and double trailing underscore _ var_
Perhaps surprisingly, if a name begins and ends with a double underscore at the same time, the name modifier is not applied. Variables surrounded by double underscore prefixes and suffixes are not modified by the Python interpreter:
Class PrefixPostfixTest: def _ init__ (self): self.__bam__ = 42 > PrefixPostfixTest (). _ _ bam__ 42
However, Python retains the name with double leading and double trailing underscore for special purposes. Examples of this are the init__ object constructor, or _ _ call-which makes an object callable.
These dunder methods are often referred to as magic methods-but many people in the Python community (including myself) don't like it.
It is best to avoid using names that begin and end with double underscores ("dunders") in your programs to avoid conflicts with future changes in the Python language.
5. Single underscore _
According to custom, sometimes a single independent underscore is used as a name to indicate that a variable is temporary or insignificant.
For example, in the following loop, we do not need to access the running index, we can use "_" to indicate that it is just a temporary value:
For _ in range (32):... Print ('Hello, World.')
You can also use a single underscore as an "unconcerned" variable in a unpacking expression to ignore a specific value. Again, this means "by contract" and does not trigger special behavior in the Python interpreter. A single underscore is just a valid variable name for this purpose.
In the following code example, I split the car tuple into separate variables, but I'm only interested in color and mileage values. However, in order for the split expression to run successfully, I need to assign all the values contained in the tuple to the variable. In this case, "_" as a placeholder variable can come in handy:
> car = ('red',' auto', 12, 3812.4) > color, _, _, mileage = car > color 'red' > mileage 3812.4 > _ 12
In addition to being used as a temporary variable, "_" is a special variable in most Python REPL that represents the result of the last expression evaluated by the interpreter.
This is convenient, for example, if you can access the results of previous calculations in an interpreter session, or if you are dynamically building multiple objects and interacting with them without assigning names to them in advance:
> 20 + 3 23 > print (_) 23 > list () [) > _ .append (1) > _ .append (2) > _ .append (3) > _ [1,2,3] so far, I believe you have a deeper understanding of what are the hidden rules of underlining in Python. You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 258
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.