Python 小知識(shí)

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文主要記錄python中常用的知識(shí)點(diǎn),每一條都針對(duì)一個(gè)小問題給出可行的解決方法。 目錄: 1.打印格式控制 2....
    Aspirinrin閱讀 935評(píng)論 0 1
  • join()方法str.join(sequence)sequence要連接的元素序列返回通過指定字符連接序列中元素...
    果三代閱讀 421評(píng)論 0 0
  • Python的兩種引入機(jī)制 Python 提供了二種引入機(jī)制: 1.relative import2.absolu...
    股金雜談閱讀 304評(píng)論 0 0
  • 帶著夢(mèng),和明天,向著月球奔去 告別憂傷,忘記憂愁, 跟著神話尋找被囚禁的嫦娥, 來吧,來吧, 來到這沒有喧囂的城市...
    青小七閱讀 239評(píng)論 0 0
  • 如果愛成為一種習(xí)慣,我們是不是會(huì)變得更勇敢一點(diǎn)?如果我們?cè)俣嘁稽c(diǎn)點(diǎn)堅(jiān)持,對(duì)自己會(huì)不會(huì)有不一樣的看法? 我覺得自己不...
    小城雅舍閱讀 294評(píng)論 0 2

友情鏈接更多精彩內(nèi)容