File tree 3 files changed +59
-0
lines changed
3 files changed +59
-0
lines changed Original file line number Diff line number Diff line change @@ -201,3 +201,34 @@ Python Cookbook中的几种方式
201
201
我猜想这么做的原因是,全局变量很危险,Python想要确保你真的知道你要对一个全局的变量进行操作
202
202
203
203
如果你想知道如何在模块间使用全局变量,查看其他回答
204
+
205
+ ### 如何检测一个变量是否存在
206
+
207
+ 问题 [ 链接] ( http://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists-in-python )
208
+
209
+ 我想检测一个变量是否存在,我现在是这么做的
210
+
211
+ try:
212
+ myVar
213
+ except NameError:
214
+ # Doint smth
215
+
216
+ 存在其他不是使用exception的方式么?
217
+
218
+ 回答
219
+
220
+
221
+ 检测本地变量
222
+
223
+ if 'myVar' in locals():
224
+ # myVar exists.
225
+
226
+ 检测全局变量
227
+
228
+ if 'myVar' in globals():
229
+ # myVar exists.
230
+
231
+ 检测一个对象是否包含某个属性
232
+
233
+ if hasattr(obj, 'attr_name'):
234
+ # obj.attr_name exists.
Original file line number Diff line number Diff line change @@ -58,3 +58,16 @@ Python 3.0 beta: 同2.6,但不支持027这种语法
58
58
59
59
c = a / float(b)
60
60
61
+ ### 如何将一个整数转为字符串
62
+
63
+ 问题 [ 链接] ( http://stackoverflow.com/questions/961632/converting-integer-to-string-in-python )
64
+
65
+ 回答
66
+
67
+ >>> str(10)
68
+ '10'
69
+ >>> int('10')
70
+ 10
71
+
72
+ 对应文档 [ int()] ( http://docs.python.org/2/library/functions.html#int ) [ str()] ( http://docs.python.org/2/library/functions.html#str )
73
+
Original file line number Diff line number Diff line change 20
20
foo = imp.load_source('module.name', '/path/to/file.py')
21
21
foo.MyClass()
22
22
23
+ ### 获取Python模块文件的路径
24
+
25
+ 问题 [ 链接] ( http://stackoverflow.com/questions/247770/retrieving-python-module-path )
26
+
27
+ 如何才能获取一个模块其所在的路径
28
+
29
+ 回答
30
+
31
+ import a_module
32
+ print a_module.__file__
33
+
34
+ 获取其所在目录,可以
35
+
36
+ import os
37
+ path = os.path.dirname(amodule.__file__)
You can’t perform that action at this time.
0 commit comments