Python類的特殊方法

2022-08-13 05:06:25 字數 2774 閱讀 6613

#

特殊方法,也稱為魔術方法

#特殊方法都是使用__開頭和結尾的

#特殊方法一般不需要我們手動呼叫,需要在一些特殊情況下自動執行

#定義乙個person類

class

person(object):

"""人類

"""def

__init__

(self, name , age):

self.name =name

self.age =age

#__str__()這個特殊方法會在嘗試將物件轉換為字串的時候呼叫

#它的作用可以用來指定物件轉換為字串的結果 (print函式)

def__str__

(self):

return

'person [name=%s , age=%d]

'%(self.name,self.age)

#__repr__()這個特殊方法會在對當前物件使用repr()函式時呼叫

#它的作用是指定物件在 『互動模式』中直接輸出的效果

def__repr__

(self):

return

'hello

''''

物件的 __dir__ 方法用於列出該物件內部的所有屬性(包括方法)名,該方法將會

返回包含所有屬性(方法)名的序列。當程式對某個物件執行 dir(object) 函式時,

實際上就是將該物件的 __dir__() 方法返回值進行排序,然後包裝成列表。

'''#

__dir__():

'''__dict__ 屬性用於檢視物件內部儲存的所有屬性名和屬性值組成的字典,通常程式直接使用

該屬性即可。程式使用 __dict__ 屬性既可檢視物件的所有內部狀態,也可通過字典語法來訪問或修改

指定屬性的值。

'''#

__dict__():

#object.__add__(self, other)

#object.__sub__(self, other)

#object.__mul__(self, other)

#object.__matmul__(self, other)

#object.__truediv__(self, other)

#object.__floordiv__(self, other)

#object.__mod__(self, other)

#object.__divmod__(self, other)

#object.__pow__(self, other[, modulo])

#object.__lshift__(self, other)

#object.__rshift__(self, other)

#object.__and__(self, other)

#object.__xor__(self, other)

#object.__or__(self, other)

#object.__lt__(self, other) 小於 <

#object.__le__(self, other) 小於等於 <=

#object.__eq__(self, other) 等於 ==

#object.__ne__(self, other) 不等於 !=

#object.__gt__(self, other) 大於 >

#object.__ge__(self, other) 大於等於 >=

#__len__()獲取物件的長度

#object.__bool__(self)

#可以通過bool來指定物件轉換為布林值的情況

def__bool__

(self):

return self.age > 17

#__gt__會在物件做大於比較的時候呼叫,該方法的返回值將會作為比較的結果

#他需要兩個引數,乙個self表示當前物件,other表示和當前物件比較的物件

#self > other

def__gt__

(self , other):

return self.age >other.age

#建立兩個person類的例項

p1 = person('

孫悟空',16)

p2 = person('

豬八戒',28)

#列印p1

#當我們列印乙個物件時,實際上列印的是物件的中特殊方法 __str__()的返回值

#print(p1) # <__main__.person object at 0x04e95090>

print

(p1)

print

(p2)

print

(repr(p1))

#t = 1,2,3

#print(t) # (1, 2, 3)

print(p1 >p2)

print(p2 >p1)

print

(bool(p1))

#if p1 :

#print(p1.name,'已經成年了')

#else :

#print(p1.name,'還未成年了')

print(p1.__dir__

())#

print(dir(p1))

#print(p1.__dict__)

#p1.__dict__["name"]="wzy"

#print(p1.__dict__["name"])

PYTHON類的特殊方法

例項1 python view plain copy coding utf 8 class firstdemo object 這裡是乙個doc a 10 類屬性 def demo self 第乙個方法 pass def demo2 self 第二個方法 pass print firstdemo.di...

Python類的特殊方法

doc描述類的資訊 class foo object 單引號和雙引號都可以 這裡描述類的資訊 def func self passprint foo.doc 這裡描述類的資訊 call物件後面加括號,觸發執行 class foo object defcall self,args,kwargs pri...

Python面試 類的特殊方法

class foo def init self print foo init def call self print foo call f foo f 過載了括號運算子 foo init foo call class decorator def init self,func print decora...