python魔术方法由谁定义_Python的魔术方法
魔術方法就是在定義的類中定義一些”不一般”的方法,使類的使用更方便、完善、健壯,是python特有的方法,一般都是前后包含兩個下劃線__的方法稱為魔術方法,例如__new__。
基本魔術方法有哪些__new__:是在一個對象實例化的時候所調用的第一個方法,用來創建類并返回這個類的實例;
class Student:
def __init__(self):
print("__init__()調用")
def __new__(cls, *args, **kwargs):
print('__new__()調用,{cls}'.format(cls=cls))
return object.__new__(cls, *args, **kwargs)
stu = Student()
# 輸出結果:
__new__()調用,
__init__()調用
很明顯可以看出,先調用了__new__方法,然后調用了__init__方法__init__:構造器,是一個初始化方法,在一個實例被創建之后調用;
__del__:析構器,當一個實例被銷毀的時候調用的方法;
__bool__:如果對象實現了bool方法,那么返回結果,非0為真,如果沒有實現bool方法,調用len方法,返回非0為真;
__hash__:返回一個整數,表明對象可以hash;
__repr__:返回對象的字符串表達式,如果沒有實現,直接返回對象內存地址字符串;
__str__:str()、print()、format()函數打印對象字符串,會直接調用str方法,如果沒有實現,會調用repr方法;
__hash__:定義當被 hash() 調用時的行為;
__bytes__:定義當被 bytes() 調用時的行為;
__format__:定義當被 format() 調用時的行為;
有關屬性魔術方法有哪些__getattr__:定義當用戶試圖獲取一個不存在的屬性時的行為;
__setattr__:定義當一個屬性被設置時的行為;
__getattribute__:定義當該類的屬性被訪問時的行為;
__delattr__:刪除一個屬性時執行的方法;
__dir__:定義當 dir() 被調用時的行為;
__get__:定義當描述符的值被取得時的行為;
__set__:定義當描述符的值被改變時的行為;
__delete__:定義當描述符的值被刪除時的行為;
運算符相關魔術方法有哪些
我們通過一小實例來看一下,有關于運算符相關的魔術方法的使用
class Student:
def __init__(self, x):
self.x = x
def __add__(self, other):
return self.x + other.x
def __sub__(self, other):
return self.x - other.x
def __mul__(self, other):
return self.x * other.x
a = Student(1)
b = Student(2)
c = Student(3)
print(b-a) # 輸出:1
print(b+a) # 輸出:3
print(b*c) # 輸出:6__add__:定義加法的方法;
__sub__:定義減法的方法;
__mul__:定義乘法的方法;
__truediv__:定義除法的方法;
__floordiv__:定義整數除法的行為://;
__mod__:定義取模算法的行為:%;
__divmod__:定義當被 divmod() 調用時的行為;
__pow__:定義當被 power() 調用或 ** 運算時的行為;
__lshift__:定義按位左移位的行為:<
__rshift__:定義按位右移位的行為:>>;
__and__:定義按位與操作的行為:&;
__xor__:定義按位異或操作的行為:^;
__or__:定義按位或操作的行為:|;
比較操作符相關魔術方法有哪些
有關于比較操作符的魔術方法也有很多,下面例子中有__eq__和__lt__的舉例,大家自己動手把所有的方法都操作一遍,就能很快理解操作符相關魔術方法的使用了
class Student(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __eq__(self, other):
return True if self.a == other.a else False
def __lt__(self, other):
if self.a < other.a:
return True
else:
return False
stu1 = Student(1, 2, 3)
stu2 = Student(3, 2, 1)
stu3 = Student(1, 2, 3)
print(stu1 == stu2) # 輸出:False
print(stu1 == stu3) # 輸出:True
print(stu1 < stu2) # 輸出:True
print(stu1 < stu3) # 輸出:False__eq__:定義等于號的方法,等價于==;
__lt__:定義小于號方法,等價于
__gt__:定義大于號方法,等價于>;
__le__:定義小于等于號的行為,等價于 <= ;
__ne__:定義不等號的行為,等價于!= ;
__ge__:定義大于等于號的行為,等價于 >= ;
容器相關的魔術方法有哪些
class Student:
def __init__(self):
self.items = {}
def __len__(self):
return len(self.items)
# 如果stu.items不為空,返回True
def __bool__(self):
return True if len(self) else False
def __iter__(self):
return iter(self.items)
def __getitem__(self, item):
return self.items[item]
def __setitem__(self, key, value):
self.items[key] = value
stu= Student()
stu.items['Course'] = 'Python'
stu.items['Teacher'] = '張三'
print(len(stu))
print(bool(stu))
print(iter(stu))
print(stu['Course'])
stu['Course'] = 'HTML'
print(stu['Course'])__len__:定義當被 len() 調用時的行為(返回容器中元素的個數);
__iter__:定義當迭代容器中的元素的行為;
__getitem__:獲取容器中的元素,相當于 self[key];
__setitem__:設置容器中的元素,相當于 self[key] = value;
__delitem__:刪除容器中的某個元素,相當于 del self[key];
__reversed__:定義當被 reversed() 調用時的行為;
__contains__:定義當使用成員測試運算符(in 或 not in)時的行為;
可調用對象
# 函數是可調用對象
def add():
pass
add.__call__()
add()
# 類實現了__call__方法
class Add():
def __call__(self, *args, **kwargs):
print(args)
print(kwargs)
add_instance = Add()
add_instance.__call__(1,2,3, course='Python')
add_instance(1,2,3,course='Python')Python中,實現了call方法的對象都是可調用對象;
__call__:允許一個類的實例像函數一樣被調用:x(a, b)調用為 x.__call__(a, b);
更多魔術方法的詳情可以參考python官網:3. Data model - Python 3.8.2 documentation?docs.python.org
學習Python推薦:俠課島_短視頻在線學習_前后端開發_產品運營_獨家原創?www.9xkd.com
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python魔术方法由谁定义_Python的魔术方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 战地5 配置要求是什么
- 下一篇: python是用来初始化_python的