In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the use of Python pit". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Indent, symbols and spaces are incorrect
When writing code, people will use indentation, alignment, spaces, etc., in order to improve the readability of the code.
But in python, many features rely on indentation.
For example, when you create a new class, everything in the class is indented under the declaration, and similar situations occur in decisions, loops, and other structural statements.
If you find a problem with code execution, you can check to see if the correct indentation is used.
Taking a look at the following example, when using if statements, be sure to use the correct and appropriate colons and indents, as they can lead to syntax and indentation errors.
Val = 500if val > 100print ("value is grater then 100") File "", line 2 if val > 100 ^ SyntaxError: invalid syntax
In the above code, there are two errors: after the if statement: missing; the next line is not indented correctly, and there is an error in the execution code.
Val = 500if val > 100:print ("value is grater then 100") value is grater then 100
When you correct the two problems in the above code, you will find that the whole code works well.
2. Misuse of class variables
Class A (object): X = 1class B (A): passclass C (A): passprint (A.x, B.x, C.x) 1 1 1
The output values here are all 1, and then let's try to change the values of A.x and B.x to see what happens.
B.x = 2print (A.x, B.x, C.X) A.x = 3print (A.x, B.x, C.x) 1 2 13 2 3
We only changed A.x, why did C.X change?
Here you need to take a brief look at the namespace of python.
In python, namespaces are a combination of name-to-object mappings, and names in different namespaces are not associated, and the implementation of this mapping is somewhat similar to a dictionary in python.
When your name accesses the properties of an object, look for it from the object's namespace first. If the property is found, the value of the property is returned; if it is not found, look in the class's namespace, return the value of the property when found, and throw an exception if it is not found.
In Python, class variables are treated internally as dictionaries and follow what is commonly referred to as the method parsing order (MRO).
The MRO:Method Resolution Order method parses the order, and Python supports multi-inheritance. This method is used to solve the ambiguity problem when the parent class has a function of the same name.
So in the above code, because x cannot find the attribute C in the object's namespace, it will look for it in the class. In other words, C has no x attribute of its own and is independent of A. Therefore, the reference to C.x actually refers to A.x.
3. Misunderstand the python scope rules
If you don't understand the scope rules of python, you can easily make mistakes because Python uses a unique scope rule to determine the scope of variables.
Python scope resolution is based on LEGB rules, and the following is an overview of Python scope rules:
L-stands for Local. It contains the (identifier / variable) name specified within the function (using def or lambda) instead of declaring it using the global keyword.
E-stands for Enclosing function locals. It contains locally scoped names from any / all closed functions (for example, using def or lambda).
G-refers to the global entity. It includes names that run at the top level of the module file or are defined using the global keyword.
B-refers to the built-in plug-in. It spans names that are pre-specified as built-in names, such as print, type, open, etc.
The LEGB rule specifies the following order of namespaces to search for names:
Local-> Enclosed-> Global-> Built-in
Consider the following examples:
X = 10def foo (): X + = 1print (x) foo () UnboundLocalError Traceback (most recent call last): in in foo () UnboundLocalError: local variable'x 'referenced before assignment
The reason for the above error is that when you assign a variable in a scope, Python automatically treats the variable as a local variable in that scope and hides any similarly named variables in the external scope.
As a result, many people are puzzled when the code prompts for an error and shows that an assignment statement needs to be added to the function.
Consider an example encountered when using a list:
Lst = [1,2,3] def foo1 (): lst.append (5) foo1 () lst [1,2,3,5] lst = [1,2,3] def foo2 (): lst + = [5] foo2 () UnboundLocalError Traceback (most recent call last): in in foo2 () UnboundLocalError: local variable 'lst' referenced before assignment
Why does foo2 go wrong but foo1 works well?
The answer has been prompted earlier, in this example, foo1 () does an assignment to lst, while in foo2 (), lst + = [5] is really just an abbreviation for lst = lst + [5]. We want to assign a value to lst, but the assigned value lst is based on lst itself, but it hasn't been defined yet.
4. Python closure variable binding
The problem of closure variables in python is also a confusing point for beginners. Let's take a look at the following example:
Def create_multipliers (): return [lambda x: I * x for i in range (5)] for multiplier in create_multipliers (): print (multiplier (2)) 88888
Why is the result 88888, which is different from the 02468 I thought?
This is due to the late binding (late binding) mechanism of Python, where the values of internal functions in closures are queried only when they are called.
Therefore, when the lambda function returned by the create_multipliers function is called, the value of the variable I is queried in the nearby scope, and after the create_multipliers generates the return array, the value of the integer I is 4, which will not change, so every anonymous function in the return array is actually: lambda x: 4roomx. 、
The solution is to save the temporary value in the scope of the anonymous function and query the value of the variable when the anonymous function is declared.
After understanding the principle, let's change the code, surprise!
Def create_multipliers (): return [lambda x, iTuni: I * x for i in range (5)] for multiplier in create_multipliers (): print (multiplier (2)) 2468
5. The name conflicts with the Python standard library module
Python has a large number of library modules that can be used out of the box. However, problems may arise if you encounter a name conflict between a module's name and a module with the same name in the standard library that ships with Python.
For example, import another library, which will try to import the Python standard library version of the module, but since you have a module with the same name, another package will mistakenly import your version instead of the Python standard library.
Therefore, care should be taken to avoid using the same name as in the Python standard library module, and it is easier to change the module name in the package than to submit a Python Enhancement Proposal (PEP) to request a name change.
6. Is and =
There are many operators in Python, such as is,=,==, and many beginners misunderstand the meaning and usage of these three operators, resulting in code errors.
Comparison between objects can be used in Python, either = = or is, but the content of object comparison is not the same. What's the difference?
Is compares whether the id values of two objects are equal, whether they point to the same memory address, = = whether the contents of the two objects are equal, and whether the values are equal.
A = ["Python"] b = ab is aTrueid (a) 2222222id (b) 2222222b = = aTrue
You can find that in the above example, the memory addresses of b and an are the same, and they point to the same block of memory, so the result of is and = = is True, because direct assignments are references to assignments. If b and a point to different memory after the new object is created, the result of b is an is False, while the result of broomrooma is True.
The small integer object [- 5256] is cached for reuse within the scope of the global interpreter, for example:
A = 1b = 1a is bTruea = = bTruea = 257b = 257a is bFalse
Python caches only smaller integer objects (in the range [- 5256]), not all integer objects. It is important to note that this is only executed on the command line, but in Pycharm or saved as a file, the results are different because the interpreter has made some optimizations.
= and = = have different meanings:
= means to assign a value to a variable, such as axi3, and to assign a value of 3 to a.
= = is to determine whether it is equal or not, and returns True or False, such as 1 equal to 1. If they are equal, then return true. If they are not equal, then return false.
Example:
A = [1mai 2] b = [1m 2] c = aa is bFalsea is ctruea = = btrue
7. Abuse of _ _ init__
The _ _ init__ method is used as a constructor in Python and is automatically called when Python allocates memory to a new class object.
First of all, _ _ init__ is not the equivalent of a constructor in C #, and the instance has already been constructed when it is executed.
Class A (object): def _ _ init__ (self,name): self.name=name def getName (self): return'A'+ self.name
Execute the code:
Afia ('hello')
It can be understood as:
A beautiful object. A new story _ (A) A.The exact initableness _ (a recordings)
That is, the function of _ _ init__ is to initialize the instantiated object.
Second, the _ _ init__, defined in the superclass is automatically called when the subclass does not override the _ _ init__ instantiation of the subclass.
Class B (A): def getName (self): return'B'+ self.nameif _ name__=='__main__': baked B ('hello') print (b.getName ())
However, if the _ _ init__, instantiation subclass is overridden, the _ _ init__ defined in the superclass will not be called implicitly.
Class C (A): def _ init__ (self): pass def getName (self): return'C'+ self.nameif _ name__=='__main__': C () print (c.getName ())
Executing the code at this point will report a "AttributeError:'C 'object has noattribute' name'" error, so if you overwrite _ _ init__, in order to use or extend the behavior in the superclass, it is best to explicitly call the _ _ init__ method of the superclass.
Class C (A): def _ _ init__ (self,name): super (Cmag self). _ init__ (name) def getName (self): return'C'+ self.nameif _ name__=='__main__': ClearC ('hello') print (c.getName ()), "what are the uses of Python pits?" Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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: 0
*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.