Python學習雜記

2021-07-23 13:52:34 字數 4840 閱讀 2243

學習資料:《python核心程式設計(第二版)》

class

c(object):

foo = 100

__name__是給定類的字元名字,它適用於那種只需要字串(類物件的名字),而非類物件本身的情況。內建的型別也有這個屬性。

>>> type('123')

...'str'>

>>> type('123').__name__

...'str'

>>> type(type('123'))

...'type'>

>>> class myclass(object):

... pass

...>>> mc = myclass()

class

instct

(object):

count = 0

# count 是乙個類屬性

def__init__

(self):

instct.count += 1

# 增加count

def__del__

(self):

instct.count -= 1

# 減少count

defhowmany

(self):

return instct.count # 返回count

設定例項的屬性可以在例項建立後任意時間進行,也可以在能夠訪問例項的**中進行。(體現python動態語言特性)
>>> c.version # 通過例項對類屬性的訪問

1.2>>> c.version += 0.2

# 相當於例項c建立了version的例項屬性,遮蔽了類屬性的訪問,不會更新類屬性

>>> c.version += 0.1

# 類屬性不變

>>> c.version # 例項再也不能訪問version類屬性了,因為已經存在同名的例項屬性

1.4

>>> class foo(object):

... x =

...>>> foo = foo()

>>> foo.x

>>> foo.x[2004] = 'valid path'

>>> foo.x # 例項訪問類屬性又可以改變類屬性了

回顧:1. 方法是類內部定義的函式(類屬性);2. 方法只有在其所屬的類用於例項時,才能被呼叫。3. 任何乙個方法定義中的第乙個引數都是變數self,表示呼叫此方法的例項物件。

例項呼叫乙個繫結方法時,self不需要明確地傳入了。而沒有例項時又需要呼叫乙個非繫結方法時,必須傳遞self引數(比如是該方法屬於類或子類的例項)

# c 和 t 兩個類, c 有foo(self)方法

>>> c = c()

>>> c.foo() # 不需要傳遞self引數

>>> c.foo(c) # 非繫結方法需要傳遞self引數

>>> t = t()

>>> c.foo(t) # self不能是除c或c子類的例項外的例項

traceback (most recent call last):

file "", line 1, in

typeerror: unbound method foo() must be called with c instance as first argument (got t instance instead)

class

c(object):

def__init__

(self, id):

self.id = id

class

child

(c):

def__init__

(self, id, age):

c.__init__(self, id) # 呼叫父類的非繫結方法,此時未創造c例項

self.age = age

# 靜態方法

class

teststaticmethod

(object):

deffoo

():print

'calling static method foo()'

foo = staticmethod(foo)

# 測試

tsm = teststaticmethod()

teststaticmethod.foo()

tsm.foo()

結果為:

calling static

method

foo()

calling

static

method

foo()

# 類方法

class

testclassmethod

(object):

deffoo

(cls, id):

print

'calling class method foo()'

print id, ': foo() is part of class:', cls.__name__

foo = classmethod(foo)

# 測試

tcm = testclassmethod()

testclassmethod.foo('001')

tcm.foo('001')

結果為:

calling class

method

foo()

001 : foo() is part of

class: testclassmethod

calling class

method

foo()

001 : foo() is part of

class: testclassmethod

# 靜態方法

class

teststaticmethod

(object):

@staticmethod

deffoo

():print

'calling static method foo()'

# 類方法

class

testclassmethod

(object):

@classmethod

deffoo

(cls, id):

print

'calling class method foo()'

print id, ': foo() is part of class:', cls.__name__

class subclassname(parentclass1[, parentclass2,...]):

'optional class documentation string'

class_suite

標記=

class

c(p):

deffoo

(self):

super(c, self).foo()

print

'hi, i am c-foo()'

# 派生基本型別(不可變型別)

class

roundfloat

(float):

def__new__

(cls, val):

return super(roundfloat, cls).__new__(cls, round(val, 2))

# 測試

x = roundfloat(1.5945)

print x

print type(x)

# 派生可變型別

# 可能不需要使用__new__方法

class

sortedkeydict

(dict):

defkeys

(self):

return sorted(super(sortedkeydict, self).keys())

# 測試

d = sortedkeydict((('zheng-cai', 67), ('hui-jun', 68), ('xin-yi', 2)))

print

'by iterator:'.ljust(12), [key for key in d]

print

'by keys():'.ljust(12), d.keys()

結果為:

by

iterator: ['zheng-cai', 'xin-yi', 'hui-jun']

by keys(): ['hui-jun', 'xin-yi', 'zheng-cai']

使用多重繼承,要考慮如何正確找到沒有在當前(子)類定義的屬性。方法解析順序

新式類也有乙個__mro__屬性,告訴我們查詢順序

菱形效應引起mro問題

>>> isinstance(int, (type,))

true

>>> isinstance(1, (int, object))

true

沒有提供引數,則將顯示乙個包含本地名字空間的屬性,即locals()

python 學習雜記

一 模組匯入問題 如果在機器上安裝了多個版本的python,往往會有匯入錯誤,例如一般的python程式頭都寫的是 usr bin env python 這個實際是 usr bin python 但是如果新版本的python是後安裝的,且沒有 prifex usr 可能這個鏈結仍指向老版本pytho...

Python 學習雜記2

類屬性 class myclass object a 0.def init self myclass.a 1 a myclass b myclass a.a2 myclass a2 b.a2 a.a 1 a.a1 myclass a2 myclass.a 10 b.a 10 python中 物件屬性...

Python學習雜記 基礎語法篇

注釋 單行注釋 多行注釋 或 python2中文相容方案 coding utf 8 變數 age 100 定義變數x賦值為100 條件判斷語句 if a 10 elif else 邏輯運算子 或 or 與 and 非 not 迴圈語句 while 迴圈 while x 9 for 迴圈 for te...