Python Programming Time is updated every Wednesday with five cold facts. Welcome to subscribe!
01. Ellipses are also objects
. This is an ellipsis. In Python, everything is an object. It is no exception.
In Python, it’s called Ellipsis.
In Python 3 you can just write… To get this thing.
> > >... Ellipsis >>> type(...) <class 'ellipsis'>Copy the code
While in 2 there is no… This syntax can only be obtained by writing Ellipsis.
>>> Ellipsis
Ellipsis
>>> type(Ellipsis)
<type 'ellipsis'>
>>>
Copy the code
It is true when converted to a Boolean value
>>> bool(...)
True
Copy the code
And finally, this thing is a singleton.
>>> id(...)
4362672336
>>> id(...)
4362672336
Copy the code
What is the use of this? It is said to be the syntactic sugar of Numpy, which is useless if you don’t play Numpy.
Only see this on the Internet with… In place of pass, it’s slightly useful, but not mandatory.
try:
1/0
except ZeroDivisionError:
...
Copy the code
02. How do I modify the interpreter prompt
Normally, we run Python commands on terminals like this.
>>> for i in range(2) :. print (i)
...
0
1
Copy the code
Have you ever thought about >>> and… Are these two prompts also modifiable?
>>> import sys
>>> sys.ps1
'> > >'
>>> sys.ps2
'... '
>>>
>>> sys.ps2 = '-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -'
>>> sys.ps1 = 'Python Programming Time >>>'Python Programming time >>>for i in range(2) : -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -print (i)
----------------
0
1
Copy the code
03. Incremental assignment performs better
Operators such as += and *= are called incremental assignment operators.
Using += as an example, the following two forms are equivalent in effect.
# the first
a = 1 ; a += 1
# the second
a = 1; a = a + 1
Copy the code
The magic method behind += is __iadd__, which if not implemented is the next best thing to use __add__.
What’s the difference between the two?
A += b = a+b = a+ B = a+ B = a+ B = a+ B = a+ B = a+ B = a+ B = a+ B = a+ B = a+ B = a+ B The new list object is then returned to the variable, which is obviously more expensive.
So use incremental assignment whenever you can.
04. Strange strings
The sample a
# Python2.7
>>> a = "Hello_Python"
>>> id(a)
32045616
>>> id("Hello" + "_" + "Python")
32045616
# Python3.7
>>> a = "Hello_Python"
>>> id(a)
38764272
>>> id("Hello" + "_" + "Python")
32045616
Copy the code
Example 2
>>> a = "MING"
>>> b = "MING"
>>> a is b
True
# Python2.7
>>> a, b = "MING!"."MING!"
>>> a is b
True
# Python3.7
>>> a, b = "MING!"."MING!"
>>> a is b
False
Copy the code
Example 3
# Python2.7
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
False
# Python3.7
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
True
Copy the code
05. The value sequence of and and or
And and or are two familiar logical operators. And we usually only use it for judgment, we rarely use it for evaluation.
If all values in an OR expression are true, Python selects the first value, and the AND expression selects the second.
> > > (2 or 3) * (5 and 7)
14 # 2 * 7
Copy the code
06. The default parameter should not be a mutable object
Function parameters are divided into three types – variable parameters – default parameters – keyword parameters
The specific differences of these three, and the use of methods in liao Xuefeng’s tutorial will be explained in detail. I’m not going to carry it here.
Today, passing in default parameters is a minefield that beginners can easily tread on.
Let’s start with an example
def func(item, item_list=[]):
item_list.append(item)
print(item_list)
func('iphone')
func('xiaomi', item_list=['oppo'.'vivo'])
func('huawei')
Copy the code
At this point, you can pause for a moment and think, what is the output?
After thinking about it, is your answer consistent with the following
['iphone']
['oppo'.'vivo'.'xiaomi']
['iphone'.'huawei']
Copy the code
If so, you can skip this part. If not, read on and analyze it here.
The def statement in Python initializes a function object each time it is executed. This function object is the function we are calling. We can think of it as a normal object, except that it has an executable method and some properties.
For arguments that provide an initial value, def is first initialized as the memory address of the mutable object, and then the default item_list argument is bound to that memory address. In subsequent function calls, if the caller specifies a new default value, the original default value is overwritten. If the caller does not specify a new default value, the old default value is used.
07. Access private methods in classes
As you all know, the only methods in a class that can be called directly are public methods (protected methods are also acceptable, but not recommended). That is, a class’s private methods cannot be called directly.
Here’s an example
class Kls(a):
def public(self):
print('Hello public world! ')
def __private(self):
print('Hello private world! ')
def call_private(self):
self.__private()
ins = Kls()
Call a public method, no problem
ins.public()
Call a private method directly, no
ins.__private()
But you can use internal public methods to delegate
ins.call_private()
Copy the code
Since all are methods, then we really don’t have methods to call directly?
Have of course, just suggest you must not do so, here just popularize, let you understand.
Call a private method, the following two are equivalent
ins._Kls__private()
ins.call_private()
Copy the code
The first letter of a class may not be capitalized
Under normal circumstances, the code we see written seems to acquiesce to the rule that class names should be capitalized and instances should be lowercase. But it’s not mandatory, and it doesn’t matter if you go the other way.
But there are some built-in classes where the first letter is all lowercase and the instance is all uppercase.
For example bool is the class name and True and False are instances; For example, ellipsis is a class name and Ellipsis is an instance; Int, string, float, list, tuple, dict, a whole bunch of data types are class names, and they’re all lowercase.
09. Occasionally abnormal section
This is a simple example
my_list = [1.2.3.4.5]
print(my_list[5])
Copy the code
Execute and, as expected, throw an index exception.
Traceback (most recent call last):
File "F:/Python Script/test.py", line 2.in <module>
print(my_list[5])
IndexError: list index out of range
Copy the code
But that’s not what I’m going to be talking about today. I’m going to be talking about something you probably didn’t know.
My_list [5:] returns a new list: [].
my_list = [1.2.3]
print(my_list[5:)Copy the code
10. When a line continuation character is not needed
When writing code, layout is very important for readability.
To achieve highly readable code, we often use the line continuation character \.
>>> a = 'talk is cheap,'\
. 'show me the code.'
>>>
>>> print(a)
talk is cheap,show me the code.
Copy the code
So what are the situations where you don’t need a line continuation?
In summary, line breaks between these symbols can omit the continuation character: [], (), {}
>>> my_list=[1.2.3.. 4.5.6]
>>> my_tuple=(1.2.3.. 4.5.6)
>>> my_dict={"name": "MING".. "gender": "male"}
Copy the code
Also, in multi-line text comments, the line continuation character may not be written.
>>> text = '''talk is cheap, ... show me the code'''
Copy the code
Just a few simple examples have been given.
But you have to learn to draw inferences. The same applies in the following scenarios
- Class and function definitions.
- List derivations, dictionary derivations, set derivations, generator expressions
11. Py2 can also use print()
I’m sure there are a lot of people out there who think that only Py3 can use print() and Py2 can only use print ‘.
That’s not the case.
Prior to Python 2.6, only support was available
print "hello"
Copy the code
In Python 2.6 and 2.7, the following three are supported
print "hello"
print("hello")
print ("hello")
Copy the code
In Python3.x, the following two are supported
print("hello")
print ("hello")
Copy the code
12. The return twice
As we all know, try… Finally… The use of statements, whether executed normally ina try or an exception, guarantees that finally will execute.
At the same time, we know that whenever a function encounters a return, it ends immediately.
So with that in mind, let’s look at this example, what does it look like?
>>> def func(a):
. try:
. return 'try'
. finally:
. return 'finally'.>>> func()
'finally'
Copy the code
Surprisingly, the return in the try does not work.
The reason is that in try… Finally… Statement, the return ina try is directly ignored to ensure that finally executes.
13. For an endless loop
The for loop is as basic as it gets.
But if you were to write an endless loop with for, would you? (Question from group friend Chen **)
This is an open question, and I suggest you try to think for yourself how you would answer it before moving on.
Well, if you don’t have any ideas, here’s the answer from an overseas MIT group:
for i in iter(int, 1):pass
Copy the code
I don’t know what to do. Is iter still used in this way? Why is this a loop?
This is really a cold knowledge, about this knowledge, if you look at the Chinese website, you may not find relevant information.
Fortunately, you can read the comments in the SOURCE code of PY through the IDE, which explains how to use it in great detail.
It turns out that there are two ways to use iter, and we usually think of the first one as converting a list to an iterator.
The second method takes a Callable object and a sentinel parameter. The first object runs until it returns a sentinel value.
What about int, again, int is a built-in method. By looking at the comments, you can see that it has a default value of 0. You can type int() on the terminal and see if it returns 0.
Since int() always returns 0, it never returns 1
These questions and answers are derived from the wisdom of the group. If you want to join our discussion, please go to the background of the official account and add my personal wechat.
14. Small integer pool
Let’s take an example.
>>> a = - 6
>>> b = - 6
>>> a is b
False
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a = 257; b = 257
>>> a is b
True
Copy the code
To avoid frequent requisition and destruction of memory space by integers, Python defines a pool of small integers [-5, 256]. These integer objects are pre-created and not garbage collected.
The above code should be tested in terminal Python. If you are testing it in an IDE, it does not look like this.
So the last example, why True?
Because when you assign the same value to two variables on the same line, the interpreter knows that the object has already been generated, so it will refer to the same object. If the split is split evenly, the interpreter does not know that the object already exists and reallocates memory for the object.
15. The mechanism of intern
As one of the most commonly used data types in Python, the Python interpreter has made many optimizations to improve the efficiency and performance of using strings.
For example, the Python interpreter uses intern technology to improve string efficiency. What is intern? That is, the same string object only holds one copy, in a string savings pool, is shared, and of course, cannot be changed, which also determines that the string must be immutable.
>>> s1="hello"
>>> s2="hello"
>>> s1 is s2
True
If there is a space, intern is not enabled by default
>>> s1="hell o"
>>> s2="hell o"
>>> s1 is s2
False
If a string is longer than 20 characters, do not activate intern
>>> s1 = "a" * 20
>>> s2 = "a" * 20
>>> s1 is s2
True
>>> s1 = "a" * 21
>>> s2 = "a" * 21
>>> s1 is s2
False
>>> s1 = "ab" * 10
>>> s2 = "ab" * 10
>>> s1 is s2
True
>>> s1 = "ab" * 11
>>> s2 = "ab" * 11
>>> s1 is s2
False
Copy the code
Reference documentation
- Farer.org/2017/11/29/…
- Github.com/satwikkansa…
- www.cnblogs.com/greatfish/p…