python中的定製類

2021-10-06 13:07:39 字數 3618 閱讀 7125

__str__()

在python中方法名如果是__***x__()的,那麼就有特殊的功能,因此叫做「魔法」方法

當使用print輸出物件的時候,只要自己定義了__str__(self)方法,那麼就會列印從在這個方法中return的資料

class student(object):

def __init__(self, name):

self.name = name

def __str__(self):

return 'student object (name: %s)' % self.name

列印:

print(student('michael'))

student object (name: michael)

__repr__()

直接顯示變數呼叫的不是__str__(),而是__repr__(),兩者的區別是__str__()返回使用者看到的字串,而__repr__()返回程式開發者看到的字串,也就是說,repr()是為除錯服務的。

在類中令__repr__ = __str__,那麼直接顯示變數也會返回 __str__裡面的return

__iter__()

class fib(object):

definit(self):

self.a, self.b = 0, 1 # 初始化兩個計數器a,b

def __iter__(self):

return self # 例項本身就是迭代物件,故返回自己

def __next__(self):

self.a, self.b = self.b, self.a + self.b # 計算下乙個值

if self.a > 100000: # 退出迴圈的條件

raise stopiteration()

return self.a # 返回下乙個值

輸出

for n in fib():

... print(n)

...1 1

2 35 ...

46368

75025

__getitem__()

1.fib例項雖然能作用於for迴圈,看起來和list有點像,但是,把它當成list來使用還是不行,比如,fib()[5]就會報錯

那麼我們可以用__getitem__()方法

class fib(object):

def __getitem__(self, n):

a, b = 1, 1

for x in range(n):

a, b = b, a + b

return a

輸出:

>>>f = fib()

>>>f[0]

1>>>f[1]

1>>> f[2]

2>>> f[3]

3>>> f[10]

89>>> f[100]

573147844013817084101

2.但list有個神奇的切片方法而fib卻會報錯

原因是__getitem__()傳入的引數可能是乙個int,也可能是乙個切片物件slice,所以要做判斷:

class fib(object):

def __getitem__(self, n):

if isinstance(n, int): # n是索引

a, b = 1, 1

for x in range(n):

a, b = b, a + b

return a

if isinstance(n, slice): # n是切片

start = n.start

stop = n.stop

if start is none:

start = 0

a, b = 1, 1

l =

for x in range(stop):

if x >= start:

a, b = b, a + b

return l

輸出:

>>> f = fib()

>>> f[0:5]

[1, 1, 2, 3, 5]

>>> f[:10]

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

__getattr__()

當我們呼叫class類中沒有出現的屬性,就會報錯,為了避免,我們寫乙個__getattr__()方法,動態返回乙個屬性

class student(object):	

def __init__(self):

self.name = 'michael'

def __getattr__(self, attr):

if attr=='score':

return 99

s = student()

>>> s.name

'michael'

>>> s.score

99

該方法也可以返回函式,注意的是:只有在沒有找到屬性的情況下,才呼叫該函式。如果呼叫其他沒有定義的屬性,則會返回none

__call__()

當我們呼叫例項方法時,我們用instance.method()來呼叫。那麼能不能直接在實列本身上呼叫呢?那麼就用到了__call__()

class student(object):

def __init__(self, name):

self.name = name

def __call__(self):

print('my name is %s.' % self.name)

輸出

>>> s = student('michael')

>>> s() # self引數不要傳入

my name is michael.

這樣我們就可以把物件看成函式,那麼怎麼判斷乙個變數是物件還是函式呢?

那麼我們通過乙個callable()函式,能被呼叫的物件就是乙個callable物件

>>> callable(student())

true

>>> callable(max)

true

>>> callable([1, 2, 3])

false

>>> callable(none)

false

>>> callable('str')

false

我的理解是不能被呼叫的物件就不是乙個callable物件,而被認為是乙個物件,而可以被呼叫的物件可以被認為就是乙個函式。

這是區分物件跟函式的標準

python定製 python中定製類

1 python中 str 和repr 如果要把乙個類的例項變成 str,就需要實現特殊方法 str classperson object def init self,name,gender self.name name self.gender genderdef str self return p...

14 python中定製類

2 python中 str 和 repr 特殊方法又稱為魔術方法 列印乙個例項 python如何把任意變數變為str的呢 因為任何資料型別的例項,都有乙個 str 的特殊方法,列印的時候實際呼叫的是這個方法 python的其餘特殊方法舉例 print的 str len的lencmp的 cmp 定義在...

python知識 定製類

如果要把乙個類的例項變成str,就需要實現特殊方法 str class person object def init self,name,gender self.name name self.gender gender def str self return person s,s self.name...