Python 特殊方法

2021-09-25 20:08:44 字數 2225 閱讀 4674

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

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

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

# 定義乙個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'

# 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('孫悟空',18)

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,'還未成年了')

python的特殊方法

來自 流暢的python 字串 位元組序列 repr str format bytes 數值轉換 abs bool complex int float hash index 集合模擬 len getitem setitem delitem contains 迭代列舉 iter reversed ne...

Python 內建特殊方法

1.資訊格式化操作 str 方法和 repr 方法 str 方法 class dog def init self,n,h self.name n self.height h def str self return 狗的名字 s n狗的體長 s self.name,self.height dog1 d...

Python特殊方法彙總

類別方法名 字串 位元組序列表示形式 repr str format bytes 數值轉換 abs bool complex int float hash index 集合模擬 len getitem setitem delitem contains 迭代列舉 iterm reversed next...