Python 黑魔法指南 v1.0
Python 黑魔法指南 v1.0
v1.0
2020 05 12
Python
wongbingming@163.com
Github https://github.com/iswbm/magic-python
01.
...
>>> ...
Ellipsis
>>> type(...)
<class 'ellipsis'>
...
>>> Ellipsis
Ellipsis
>>> type(Ellipsis)
<type 'ellipsis'>
>>>
>>> bool(...)
True
>>> id(...)
4362672336
>>> id(...)
4362672336
$ cat demo.py
def func01():
...
def func02():
pass
func01()
func02()
print("ok")
$ python3 demo.py
ok
02. end
__builtins__.end = None
def my_abs(x):
if x > 0:
return x
else:
return -x
end
end
print(my_abs(10))
print(my_abs(-10))
03. zip
[root@localhost ~]# ls -l demo
total 8
-rw-r--r-- 1 root root 30 May 8 19:27 calc.py
-rw-r--r-- 1 root root 35 May 8 19:33 __main__.py
[root@localhost ~]#
[root@localhost ~]# cat demo/__main__.py
import calc
print(calc.add(2, 3))
[root@localhost ~]#
[root@localhost ~]# cat demo/calc.py
def add(x, y):
return x+y
[root@localhost ~]#
[root@localhost ~]# python -m zipfile -c demo.zip demo/*
[root@localhost ~]#
04. :
>>> str1='\nhello'
>>> print(str1)
hello
>>> str2='\thello' tab
>>> print(str2)
hello
>>> str3="\"
File "<stdin>", line 1
str3="\"
^
SyntaxError: EOL while scanning string literal
>>> str3=r"\"
File "<stdin>", line 1
str3=r"\"
^
SyntaxError: EOL while scanning string literal
05. for
for i in iter(int, 1):pass
int
int()
06. “_”
_
>>> 3 + 4
7
>>> _
7
>>> name=' : Python '
>>> name
' : Python '
>>> _
' : Python '
>>> 3 + 4
7
>>> _
7
>>> print(" : Python ")
ming
>>> _
7
__repr__
# demo.py
class mytest():
def __str__(self):
return "hello"
def __repr__(self):
return "world"
07.
>>>(2 or 3) * (5 and 7)
14 # 2*7
09.
>>> ...
10.
print(func())
[root@localhost ~]# python3 demo.py
('ok',)
11.
func('iphone')
func('xiaomi', item_list=['oppo','vivo'])
func('huawei')
['iphone']
['oppo', 'vivo', 'xiaomi']
['iphone', 'huawei']
12.
class Kls():
def public(self):
print('Hello public world!')
def __private(self):
print('Hello private world!')
def call_private(self):
self.__private()
ins = Kls()
#
ins.public()
#
ins.__private()
#
ins.call_private()
#
ins._Kls__private()
ins.call_private()
13.
14.
\
[] () {}
>>> my_list=[1,2,3,
... 4,5,6]
>>> my_tuple=(1,2,3,
... 4,5,6)
'''
print ""
print "hello"
print "hello"
print("hello")
print ("hello")
print("hello")
print ("hello")
16.
# Python2.7
>>> a = "Hello_Python"
>>> id(a)
32045616
>>> id("Hello" + "_" + "Python")
32045616
# Python3.7
>>> a = "Hello_Python"
>>> id(a)
38764272
>>> id("Hello" + "_" + "Python")
32045616
>>> 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
# Python2.7
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
False
# Python3.7
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
True
17. return
>>> def func():
... try:
... return 'try'
... finally:
... return 'finally'
...
>>> func()
'finally'
18.
>>> a = -6
>>> b = -6
>>> a is b
False
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
19. intern
>>> s1="hello"
>>> s2="hello"
>>> s1 is s2
True
# intern
>>> s1="hell o"
>>> s2="hell o"
>>> s1 is s2
False
# 20 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
20. /
>>> ml = [1,2,3,4,5]
>>> ml.reverse()
>>> ml
[5, 4, 3, 2, 1]
mstr1 = 'abc'
ml1 = list(mstr1)
ml1.reverse()
mstr2 = str(ml1)
def my_reverse(str):
if str == "":
return str
else:
return my_reverse(str[1:]) + str[0]
>>> sys.setrecursionlimit(2000)
>>> sys.getrecursionlimit()
2000
22. FTP
# python2
python -m SimpleHTTPServer 8888
# python3
python3 -m http.server 8888
23. else
else:
print("Does not exist")
test_try_else()
# Exception occurred...
test_try_else("ming")
# No Exception occurred...
24.
>>> "aabb".count("a")
2
>>> "aabb".count("b")
2
>>> "aabb".count("ab")
1
>>> "aabb".count("")
5
aabb
>>> (" " * 10).count("")
11
>>>
>>> "" in ""
True
>>>
>>> "" in "M"
True
25.
>>> 5-3
2
>>> 5--3
8
>>> 5+-3
2
>>> 5++3
8
>>> 5---3
2
26.
27.
# Python2
>>> x = 1
>>> [x for x in range(5)]
[0, 1, 2, 3, 4]
>>> x
4
# Python3
>>> x = 1
>>> [x for x in range(5)]
[0, 1, 2, 3, 4]
>>> x
1
28.
# Python2.7.10
>>> mydict = {str(i):i for i in range(5)}
>>> mydict
{'1': 1, '0': 0, '3': 3, '2': 2, '4': 4}
# Python3.6.7
>>> mydict = {str(i):i for i in range(5)}
>>> mydict
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}
29. import
antigravity
# demo.py
a = 1
def add():
a += 1
add()
$ python demo.py
Traceback (most recent call last):
File "demo.py", line 6, in <module>
add()
File "demo.py", line 4, in add
a += 1
UnboundLocalError: local variable 'a' referenced before assignment
a += 1 a
a
$ cat demo.py
a = 1
def output():
print(a)
output()
$ python demo.py
1
31.
>>> valuе = 32
File "<stdin>", line 1
valuе = 32
^
SyntaxError: invalid syntax
>>> valuе = 32
>>> value
11
valuе = 32
е e
e
e
32.
\n
>>> str.split('\n')
['a', 'b', '']
>>>
splitlines
>>> str.splitlines()
['a', 'b']
33.
import contextlib
@contextlib.contextmanager
def test_context(name):
print('enter, my name is {}'.format(name))
yield
with test_context('aaa'):
with test_context('bbb'):
print('========== in main ============')
34. += =+
+= =+
# =+
>>> a = [1, 2, 3, 4]
>>> b = a
>>> a = a + [5, 6, 7, 8]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4]
# +=
>>> a = [1, 2, 3, 4]
>>> b = a
>>> a += [5, 6, 7, 8]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]
35.
+= *=
#
a = 1 ; a += 1
#
a = 1; a = a + 1
+=
36. x == +x
>>> n1 = 10086
>>> n2 = +n1
>>>
>>> n1 == n2
True
+ <=
37. print
$ cat test.log
hello, python
38. site-packages dist-packages
"error" parameter
def output_msg(msg):
print(msg)
output_msg("error")
40.
41.
>>> a = [1,2]
>>> b = [3,4]
>>> c = [5,6]
>>>
>>> sum((a,b,c), [])
[1, 2, 3, 4, 5, 6]
42. 8
itertools.chain()
sorted(itertools.chain(*iterables))
__add__
__add__
43.
clean()
atexit.register(clean_1, 1, 2, 3='xxx')
os._exit()
44. 8
** {}
dict(**profile, **ext_info)
ChainMap itertools
|
items
| |=
45.
if age > 18:
return " "
else:
return " "
>>> age1 = 20
>>> age2 = 17
>>>
>>>
>>> msg1 = " " if age1 > 18 else " "
>>> print msg1
>>>
>>> msg2 = " " if age2 > 18 else " "
>>> print msg2
>>>
>>>
>>> print(msg2)
(<on_true>, <on_false>)[condition]
>>>
>>>
>>> msg2 = (" ", " ")[age2 > 18]
>>> print(msg2)
>>> msg1 = {True: " ", False: " "}[age1 > 18]
>>> print(msg1)
>>>
>>> msg2 = {True: " ", False: " "}[age2 > 18]
>>> print(msg2)
>>> msg1 = ((age1 > 18) and (" ",) or (" ",))[0]
>>> print(msg1)
>>>
>>> msg2 = ((age2 > 18) and (" ",) or (" ",))[0]
>>> print(msg2)
46. /usr/bin/env python
#!/usr/bin/python
#!/usr/bin/env python
/usr/bin/python python
python
#! /usr/bin/python
python xx.py
python
#!/usr/bin/python
!/usr/bin/env python
env python
env python env | grep PATH
/usr/bin/python PATH
/usr/local/sbin
/usr/bin/python
#!/usr/bin/env python
/usr/bin/python
47.
#
[wangbm@localhost ~]$ pip list | grep requests
[wangbm@localhost ~]$ pip install --user requests
[wangbm@localhost ~]$ pip list | grep requests
requests (2.22.0)
[wangbm@localhost ~]$
# Location requests
[wangbm@localhost ~]$ pip show requests
---
Metadata-Version: 2.1
Name: requests
Version: 2.22.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.org
Installer: pip
License: Apache 2.0
Location: /home/wangbm/.local/lib/python2.7/site-packages
[wangbm@localhost ~]$ exit
logout
48. defer
import "fmt"
func myfunc() {
fmt.Println("B")
}
func main() {
defer myfunc()
fmt.Println("A")
}
A
B
import contextlib
def callback():
print('B')
A
B
49.
@functools.lru_cache(maxsize=None, typed=False)
@lru_cache(None)
def add(x, y):
print("calculating: %s + %s" % (x, y))
return x + y
print(add(1, 2))
print(add(1, 2))
print(add(2, 3))
calculating: 1 + 2
3
3
calculating: 2 + 3
5
50.
import contextlib
log_file="/var/log/you.log"
def you_task():
pass
@contextlib.contextmanager
def close_stdout():
raw_stdout = sys.stdout
file = open(log_file, 'a+')
sys.stdout = file
yield
sys.stdout = raw_stdout
file.close()
with close_stdout():
you_task()