1. if name == 'main' 作用
简单来说,就是这个语句只有在这个文件自己被执行的时候才会true执行,被别的文件引用的时候就不会执行。从而方便测试。
浅析python 中name = 'main' 的作用
2. GUI 之 Tkinter
3.print和sys.stdout.write
print(obj)
内部就是sys.stdout.\write(obj+'\n')
4.单引号和双引号
s1 = 'string'
s2 = "string"
s3 = '"' #被单引号包含时双引号不用转义
s4 = "'" #被双引号包含时单引号不用转义
5.With语句
with 语句执行紧跟着的对象的enter()方法,然后将返回值赋予as部分,最后执行exit()方法。
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print "type:", type
print "value:", value
print "trace:", trace
def do_something(self):
bar = 1/0
return bar + 10
with Sample() as sample:
sample.do_something()
输出:
type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback
(most recent call last):
File "./with_example02.py",
line 19, in <module>
sample.do_something()
File "./with_example02.py",
line 15, in do_something
bar = 1/0
ZeroDivisionError:
integer division or modulo by zero
6. 共享类变量
class Counter:
count = 0
def __init__(self):
print("Do a test")
def plus(self):
self.count = self.count + 1
print(self.count)
a = counter()
b = counter()
a.plus()
b.plus()
// 1
// 1
class Counter:
count = 0
def __init__(self):
print("Do a test")
def plus(self):
Counter.count = Counter.count + 1
print(Counter.count)
a = counter()
b = counter()
a.plus()
b.plus()
// 1
// 2