It takes about 3.6 minutes to read this article.
I first selected 6 python codes that I think are worthy of fun. I hope it will be helpful to you who are learning python.
**1、 The class has two methods, one is new and the other is init. What is the difference, which one will execute first? **
classtest(object):
def __init__(self):print("test -> __init__")
def __new__(cls):print("test ->__new__")returnsuper().__new__(cls)
a =test()
The results are as follows:
test ->__new__
test -> __init__
Let's look at another example
classtest2(object):
def __init__(self):print("test2 -> __init__")
def __new__(cls):print("test2 ->__new__")returnobject()
b =test2()
The results are as follows:
test2 ->__new__
Here is an official explanation: The function of init is to initialize the class instance, the first parameter is self, which represents the object itself, and there is no return value. new returns an instance of a new class. The first parameter is cls, which represents the class itself and must have a return value. Obviously, a class can be instantiated before it can produce objects. Obviously, new is executed first, and then init. In fact, as long as new returns an instance of the class itself, it will automatically call init to initialize. But there are exceptions. If new returns an instance of another class, it will not call the init of the current class. Below we respectively output the types of object a and object b:
print(type(a))
#< class'__main__.test'>print(type(b))
#< class'object'>
It can be seen that a is an object of test class, and b is an object of object.
Reference documents:
https://docs.python.org/3/reference/datamodel.html?highlight=new#object.new
2、 Object returned by map function
The first parameter of the map() function is fun, and the second parameter is generally a list. The third parameter can be written list or not. The function is to call the function fun sequentially on each element of the list in the list.
>>> b=map(lambda x:x*x,[1,2,3])>>>[i for i in b][1,4,9]>>>[i for i in b][]>>>
Have you noticed that when you output the element in b for the second time, it was found to be empty. The reason is that the map() function returns an iterator and uses yield for the returned result. The purpose of this is to save memory.
for example:
# encoding:UTF-8
def yield_test(n):for i inrange(n):yieldcall(i)
# Do some other things
def call(i):return i*2
# Use for loop
x =yield_test(5)print([i for i in x])print([i for i in x])
The execution result is:
[0,2,4,6,8][]
If yield is not used here, when the elements in the list are very large, they will all be loaded into memory, which is a waste of memory and also reduces efficiency.
For an introduction to iterators, see the previous article: [python basic series-iterable objects, iterators and generators] (http://mp.weixin.qq.com/s?__biz=MzU0OTg3NzU2NA==&mid=2247483827&idx=1&sn=6a661c78b3f0db2e4c94cee1ddc3b036&chksm=fba863e0ccdfeaf628a112bcfe9401b3933fe5b359e17ff4345d6fcfddf7103c4460cd3d1c5d&scene=21#wechat_redirect).
**3、 Is compile unnecessary in regular expressions? **
For example, there is a demand for text
>>> import re
>>> text ='<div class="nam">China</div>'>>> #method one
...>>> re.findall('<div class=".*">(.*)</div>',text)['China']>>> #Method Two
...>>> regex='<div class=".*">(.*)</div>'>>> pattern = re.compile(regex)>>> re.findall(pattern,text)['China']>>>
Why use compile to write two more lines of code here? The reason is that compile compiles the regular expression into an object, speeds it up, and reuses it.
4、[[1,2],[3,4],[5,6]] Expand the list with one line of code and get [1,2,3,4,5,6]
>>>[ j for i in[[1,2],[3,4],[5,6]]for j in i][1,2,3,4,5,6]>>>
5、 One line of code inserts the string "->" into the middle of each character in "abcdefg"
>>>"- >". join("abcdef")'a->b->c->d->e->f'>>>
It is also recommended to use os.path.join() to join the file path of the operating system.
6、 zip function
When the zip() function operates, it takes one or more sequences (iterable objects) as parameters and returns a list of tuples. At the same time, pair the side-by-side elements in these sequences. The zip() parameter can accept any type of sequence, and it can also have more than two parameters; when the length of the incoming parameters is different, zip can automatically intercept the shortest sequence length to obtain tuples.
>>> a=[1,2]>>> b=(3,4)>>>zip(a,b)<zip object at 0x000001A20201AA08>>>>for i inzip(a,b):...print(i)...(1,3)(2,4)>>> a="ab">>> b="xyz">>>for i inzip(a,b):...print(i)...('a','x')('b','y')>>>
( Finish)
Recommended Posts