Python Tutorial

Python 3

Built-in objects preview

Object type Example literals/creation
Numbers 1234, 3.1415, 3+4j, Decimal, Fraction
Strings 'spam', "guido's", b'a\xolc'
Lists [1,[2,'three'],4]
Dictionaries {'foo':'spam','taste':'yum'}, dict(hours=10)
Tuples (1,'spam',4,'U'), tuple('spam')
Files myfile=open('eggs','r'), _myfile=open(r'C:\ham.bin','wb')
Sets set('abc'), {'a','b','c'}
Other core types Booleans, types, None
Program unit types Functions, modules, classes
Implementation-related types Complied code, stack tracebacks

列表是一个序列,其元素是有序的,字典更像是映射(key -> value),元组根本上就是一个不可以改变的列表,集合是唯一的可变的对象的无序集合。

寻求帮助

使用 dir 函数可以查看对象的所有属性(方法也是对象的属性),使用 help 函数可以查看具体的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> S = '123'
>>> dir(S)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
>>> help(S.replace)
Help on built-in function replace:

replace(...) method of builtins.str instance
S.replace(old, new[, count]) -> str

Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.

>>>

Python 编码规范

使用 pylint 进行代码检查

在 Windows 下安装 pylint :

1
pip install pylint

编写批处理测试脚本 pylint.bat ,方便测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@echo off

set python_file=%~1
for /f "tokens=2,*" %%i in ('reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"') do set desktop=%%j
set output_dir=%desktop:~0,-1%\pylint_log.txt
call pylint %python_file% > %output_dir%

:pylint
::---------pylint结果输出到文件
::---------参数%1为python文件
::---------调用:call :pylint test.py
::@echo off
set python_f = %~1
if not defined python_f goto :eof
pylint %python_f%
goto :eof

pylint.bat 使用:

1
2
3
4
C:\Users\Leo>C:\Users\Leo\Desktop\pylint.bat F:\eclipse\workspaces\20140719\OOMMonitor\OOMMonitor.py
No config file found, using default configuration

C:\Users\Leo>

输出结果在桌面的 pylint_log.txt 文件中,内容大致如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
************* Module OOMMonitor
R: 98, 0: Too many instance attributes (16/7) (too-many-instance-attributes)
E:125,38: Module 'win32event' has no 'CreateEvent' member (no-member)
C:147, 4: Invalid method name "SvcStop" (invalid-name)
E:152,46: Module 'win32service' has no 'SERVICE_STOP_PENDING' member (no-member)
E:154,19: Module 'win32event' has no 'SetEvent' member (no-member)
C:156, 4: Invalid method name "SvcDoRun" (invalid-name)
W:164,15: Catching too general exception Exception (broad-except)
E:171,19: Module 'win32event' has no 'WaitForSingleObject' member (no-member)
E:171,68: Module 'win32event' has no 'INFINITE' member (no-member)
W:203,26: Unused variable 'dirs' (unused-variable)
W:232,15: Catching too general exception Exception (broad-except)
W:281,23: Catching too general exception Exception (broad-except)
W:465,19: Catching too general exception Exception (broad-except)



Report

======

296 statements analysed.



Statistics by type

------------------


+---------+-------+-----------+-----------+------------+---------+
|type |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module |1 |1 |= |100.00 |0.00 |
+---------+-------+-----------+-----------+------------+---------+
|class |1 |1 |= |100.00 |0.00 |
+---------+-------+-----------+-----------+------------+---------+
|method |15 |15 |= |100.00 |13.33 |
+---------+-------+-----------+-----------+------------+---------+
|function |5 |5 |= |100.00 |0.00 |
+---------+-------+-----------+-----------+------------+---------+






External dependencies

---------------------

::


bs4 (OOMMonitor)

win32event (OOMMonitor)

win32service (OOMMonitor)

win32serviceutil (OOMMonitor)







Raw metrics

-----------


+----------+-------+------+---------+-----------+
|type |number |% |previous |difference |
+==========+=======+======+=========+===========+
|code |303 |68.86 |303 |= |
+----------+-------+------+---------+-----------+
|docstring |92 |20.91 |92 |= |
+----------+-------+------+---------+-----------+
|comment |9 |2.05 |9 |= |
+----------+-------+------+---------+-----------+
|empty |36 |8.18 |36 |= |
+----------+-------+------+---------+-----------+






Duplication

-----------


+-------------------------+------+---------+-----------+
| |now |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines |0 |0 |= |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000 |= |
+-------------------------+------+---------+-----------+






Messages by category

--------------------


+-----------+-------+---------+-----------+
|type |number |previous |difference |
+===========+=======+=========+===========+
|convention |2 |2 |= |
+-----------+-------+---------+-----------+
|refactor |1 |1 |= |
+-----------+-------+---------+-----------+
|warning |5 |5 |= |
+-----------+-------+---------+-----------+
|error |5 |5 |= |
+-----------+-------+---------+-----------+






Messages

--------


+-----------------------------+------------+
|message id |occurrences |
+=============================+============+
|no-member |5 |
+-----------------------------+------------+
|broad-except |4 |
+-----------------------------+------------+
|invalid-name |2 |
+-----------------------------+------------+
|unused-variable |1 |
+-----------------------------+------------+
|too-many-instance-attributes |1 |
+-----------------------------+------------+






Global evaluation

-----------------

Your code has been rated at 8.89/10 (previous run: 8.89/10, +0.00)

输出内容中的 R,E,C 等代表的是 MESSAGE_TYPE ,其含义如下:

(C) 惯例。违反了编码风格标准

(R) 重构。写得非常糟糕的代码。

(W) 警告。某些 Python 特定的问题。

(E) 错误。很可能是代码中的错误。

(F) 致命错误。阻止 Pylint 进一步运行的错误。

Python 打包工具

Python metaclass

原地址:What is a metaclass in Python?

译文 :深刻理解Python中的元类(metaclass)

Python’s abc module

详细讲解地址:Abstract Base Classes in Python

推荐文章

Python技术文章收集:PyZh