gj3 Python数据模型(魔法函数)
生活随笔
收集整理的這篇文章主要介紹了
gj3 Python数据模型(魔法函数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
3.1 什么是魔法函數
??? 類里面,實現某些特性的內置函數,類似 def __xx__(): 的形式。 不要自己定義XX,并不是和某個類掛鉤的
class Company(object):def __init__(self, employee_list):self.employee = employee_list# 可迭代def __getitem__(self, item):return self.employee[item]# 長度,實現了len函數def __len__(self):return len(self.employee)company1 = Company(["tom", "bob", "jane"]) # # company1= company[:2] # # print(len(company))for em in company1:print(em)3.2 python的數據模型以及數據模型對python的影響
只要實現了對應的數據模型,就具有該模型的特性
3.3 魔法函數一覽
???? 3.3.1 非數學運算
字符串表示
__repr__? 開發模式下調用的
__str__?? 對對象進行字符串格式化時調用
class Company(object):def __init__(self, employee_list):self.employee=employee_listdef __str__(self):print("str called")return",". join(self. employee)def __repr__(self):print("repr called")return",". join(self. employee) company=Company(["tom","bob","jane"]) company # repr(company) # company.__repr__() # print(company)repr called tom,bob,jane Python數據模型(魔法函數)非數學運算字符串表示__repr____str__集合、序列相關__len____getitem____setitem____delitem____contains__迭代相關__iter____next__可調用__call__with上下文管理器__enter____exit__數值轉換__abs____bool____int____float____hash____index__元類相關__new____init__屬性相關__getattr__、 __setattr____getattribute__、setattribute____dir__屬性描述符__get__、__set__、 __delete__協程__await__、__aiter__、__anext__、__aenter__、__aexit__ Python數據模型(魔法函數)--非數學運算3.3.2 數學運算
一元運算符__neg__(-)、__pos__(+)、__abs__二元運算符__lt__(<)、 __le__ <= 、 __eq__ == 、 __ne__ != 、 __gt__ > 、 __ge__ >=算術運算符__add__ + 、 __sub__ - 、 __mul__ * 、 __truediv__ / 、 __floordiv__ // 、 __ mod__ % 、 __divmod__ divmod() 、 __pow__ ** 或 pow() 、 __round__ round()反向算術運算符__radd__ 、 __rsub__ 、 __rmul__ 、 __rtruediv__ 、 __rfloordiv__ 、 __rmod__ 、 __rdivmod__ 、 __rpow__增量賦值算術運算符__iadd__ 、 __isub__ 、 __imul__ 、 __itruediv__ 、 __ifloordiv__ 、 __imod__ 、 __ipow__位運算符__invert__ ~ 、 __lshift__ << 、 __rshift__ >> 、 __and__ & 、 __or__ | 、 __ xor__ ^反向位運算符__rlshift__ 、 __rrshift__ 、 __rand__ 、 __rxor__ 、 __ror__增量賦值位運算符__ilshift__ 、 __irshift__ 、 __iand__ 、 __ixor__ 、 __ior__ 數學運算 class Nums(object):def __init__(self,num):self.num=numdef __abs__(self):return abs(self.num) my_num=Nums(1) abs(my_num) 1 ? class MyVector(object):def __init__(self, x, y):self.x = xself.y = ydef __add__(self, other_instance):re_vector = MyVector(self.x + other_instance.x, self.y + other_instance.y)return re_vectordef __str__(self):return "x:{x},y:{y}".format(x=self.x, y=self.y) ? ? first_vec = MyVector(1, 2) second_vec = MyVector(2, 3) print(first_vec + second_vec) ? x:3,y:53.4 隨便舉個例子說明魔法函數的重要性(len函數)
len(set dict list) 會直接調用set dict list數據類型本身cpython的內置實現
在任何對象中都可以去實現魔法函數
只要實現了對應的魔法函數,就能實現Python某些數據類型的功能
總結
以上是生活随笔為你收集整理的gj3 Python数据模型(魔法函数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gj2 python中一切皆对象
- 下一篇: gj4 深入类和对象