1. if name == 'main' 作用
簡(jiǎn)單來說,就是這個(gè)語(yǔ)句只有在這個(gè)文件自己被執(zhí)行的時(shí)候才會(huì)true執(zhí)行,被別的文件引用的時(shí)候就不會(huì)執(zhí)行。從而方便測(cè)試。
淺析python 中name = 'main' 的作用
2. GUI 之 Tkinter
3.print和sys.stdout.write
print(obj)內(nèi)部就是sys.stdout.\write(obj+'\n')
4.單引號(hào)和雙引號(hào)
s1 = 'string'
s2 = "string"
s3 = '"' #被單引號(hào)包含時(shí)雙引號(hào)不用轉(zhuǎn)義
s4 = "'" #被雙引號(hào)包含時(shí)單引號(hào)不用轉(zhuǎn)義
5.With語(yǔ)句
with 語(yǔ)句執(zhí)行緊跟著的對(duì)象的enter()方法,然后將返回值賦予as部分,最后執(zhí)行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