python內建函式和魔法函式

2021-09-07 18:52:10 字數 4160 閱讀 1574

內建方法:python中宣告每乙個類系統都會加上一些缺省內置方法,提供給系統呼叫該類的物件時使用。比如需要例項化乙個物件時,需要呼叫該類的init方法;使用print去列印乙個類時,其實呼叫的是str方法等等。

內建變數:

class

myvector(object):

def__init__

(self, x, y):

self.x =x

self.y =y

def__add__

(self, other_instance):

re_vector = myvector(self.x+other_instance.x, self.y+other_instance.y)

return

re_vector

def__str__

(self):

return

"x:, y:

".format(x=self.x, y=self.y)

first_vec = myvector(1,2)

second_vec = myvector(2,3)

print(first_vec+second_vec)

操作符過載:通過定義類的一些約定的以"__"開頭並結尾的函式,可以到達過載一些特定操作的目的

__str__ / __unicode__       

當print乙個物件例項時,實際是print該例項 .str()函式的返回值:

class

a:

def__str__

(self):

return"a

"def

__unicode__

(self):

return"ua

"

魔法函式有什麼作用?

魔法函式可以為你寫的類增加一些額外功能,方便使用者理解。舉個簡單的例子,我們定義乙個「人」的類people,當中有屬性姓名name、年齡age。讓你需要利用sorted函式對乙個people的陣列進行排序,排序規則是按照name和age同時排序,即name不同時比較name,相同時比較age。由於people類本身不具有比較功能,所以需要自定義,你可以這麼定義people類:

class

people(object):

def__init__

(self, name, age):

self.name =name

self.age =age

return

def__str__

(self):

return self.name + "

:" +str(self.age)

def__lt__

(self, other):

return self.name < other.name if self.name != other.name else self.age if__name__=="

__main__":

print("

\t".join([str(item) for item in sorted([people("

abc", 18), people("

abe", 19), people("

abe", 12), people("

abc", 17)])]))

python中每個魔法函式都對應了乙個python內建函式或操作,比如__str__對應str函式,__lt__對應小於號《等。python中的魔法函式可以大概分為以下幾類:

類的構造、刪除:

object.__new__(self, ...) object.__init__(self, ...) object.__del__(self) 

二元操作符:

+	object.__add__(self, other) - object.__sub__(self, other) * object.__mul__(self, other) // object.__floordiv__(self, other) / object.__div__(self, other) % object.__mod__(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.__iadd__(self, other) -= object.__isub__(self, other) *= object.__imul__(self, other) /= object.__idiv__(self, other) //= object.__ifloordiv__(self, other) %= object.__imod__(self, other) **= object.__ipow__(self, other[, modulo]) <<= object.__ilshift__(self, other) >>= object.__irshift__(self, other) &= object.__iand__(self, other) ^= object.__ixor__(self, other) |= object.__ior__(self, other) 

一元操作符:

-	object.__neg__(self) + object.__pos__(self) abs() object.__abs__(self) ~ object.__invert__(self) complex() object.__complex__(self) int() object.__int__(self) long() object.__long__(self) float() object.__float__(self) oct() object.__oct__(self) hex() object.__hex__(self) round() object.__round__(self, n) floor() object__floor__(self) ceil() object.__ceil__(self) trunc() object.__trunc__(self) 

比較函式:

<	object.__lt__(self, other) <= object.__le__(self, other) == object.__eq__(self, other) != object.__ne__(self, other) >= object.__ge__(self, other) > object.__gt__(self, other) 

類的表示、輸出:

str()	object.__str__(self) repr() object.__repr__(self) len() object.__len__(self) hash() object.__hash__(self) bool() object.__nonzero__(self) dir() object.__dir__(self) sys.getsizeof() object.__sizeof__(self) 

類容器:

len()	object.__len__(self) self[key] object.__getitem__(self, key) self[key] = value object.__setitem__(self, key, value) del[key] object.__delitem__(self, key) iter() object.__iter__(self) reversed() object.__reversed__(self) in操作 object.__contains__(self, item) 字典key不存在時 object.__missing__(self, key)

python 內建函式 魔法屬性 詳解

3.魔法屬性 3.2 repr 例項視覺化 3.3 eq 判等,hash 計算hash值 map是乙個將乙個或多個序列對映成乙個序列的函式。第乙個引數為function,function可以是單或多引數。接著是乙個或多個序列。例如 reduce對序列的返回值進行累加。counter類,它是dict的...

python高階之函式和類內建魔法屬性

關於物件的魔法方法我們已經講得太多,但是對於類或函式內建的魔法屬性和功能我們涉及較少,下面系統了解一下類和函式的內建屬性。class person object pass def get name pass if name main person person print dir get name ...

python魔法函式

python中魔法函式簡單上來說就是在構建某個類的時候,給類定義一些初始的方法,來實現類物件的某些屬性或者方法而準備。其形式如下,下雙劃線開頭雙劃線結尾 初始化乙個學生class class student def init self,students list self.students list...