日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當(dāng)前位置:首頁(yè) > 科技  > 軟件

Python中的雙下劃線:特殊方法和屬性的魔法世界!

來(lái)源: 責(zé)編: 時(shí)間:2023-11-09 09:14:34 269觀看
導(dǎo)讀Python中的特殊方法和屬性,我們可以了解到這些功能是如何為自定義類和對(duì)象提供強(qiáng)大的控制和自定義選項(xiàng)的。這些特殊方法和屬性具有特定的名稱和用途,以雙下劃線__開(kāi)頭和結(jié)尾。它們?cè)试S覆蓋默認(rèn)行為,從而實(shí)現(xiàn)更靈活的對(duì)象

cdl28資訊網(wǎng)——每日最新資訊28at.com

Python中的特殊方法和屬性,我們可以了解到這些功能是如何為自定義類和對(duì)象提供強(qiáng)大的控制和自定義選項(xiàng)的。cdl28資訊網(wǎng)——每日最新資訊28at.com

這些特殊方法和屬性具有特定的名稱和用途,以雙下劃線__開(kāi)頭和結(jié)尾。它們?cè)试S覆蓋默認(rèn)行為,從而實(shí)現(xiàn)更靈活的對(duì)象交互和自定義類的行為。cdl28資訊網(wǎng)——每日最新資訊28at.com

特殊方法(Magic Methods)

1、 __init__(self, ...): 構(gòu)造方法

__init__是在創(chuàng)建新對(duì)象時(shí)首先調(diào)用的方法。用于初始化對(duì)象的屬性和執(zhí)行任何必要的設(shè)置。通常會(huì)在自定義類中定義的第一個(gè)方法。cdl28資訊網(wǎng)——每日最新資訊28at.com

class Person:    def __init__(self, name, age):        self.name = name        self.age = age

2、 __str__(self): 字符串表示

__str__方法定義了對(duì)象的字符串表示。使用str(obj)print(obj)時(shí),將調(diào)用此方法。cdl28資訊網(wǎng)——每日最新資訊28at.com

class Person:    def __str__(self):        return f"{self.name}, {self.age} years old"

3、 __repr__(self): 官方字符串表示

__repr__方法返回對(duì)象的"官方"字符串表示,通常是一個(gè)可以用來(lái)重新創(chuàng)建該對(duì)象的表達(dá)式。它對(duì)于調(diào)試和開(kāi)發(fā)非常有用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class Person:    def __repr__(self):        return f"Person('{self.name}', {self.age})"

4、__len__(self): 長(zhǎng)度

__len__方法定義了對(duì)象的長(zhǎng)度,可以通過(guò)len(obj)來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyList:    def __init__(self, items):        self.items = items    def __len__(self):        return len(self.items)

5、__getitem__(self, key): 獲取元素

__getitem__方法用于通過(guò)鍵或索引訪問(wèn)對(duì)象的元素,可通過(guò)obj[key]來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyList:    def __getitem__(self, index):        return self.items[index]

6、__setitem__(self, key, value): 設(shè)置元素

__setitem__方法允許您通過(guò)鍵或索引設(shè)置對(duì)象的元素,可通過(guò)obj[key] = value來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyList:    def __setitem__(self, index, value):        self.items[index] = value

7、__delitem__(self, key): 刪除元素

__delitem__方法定義了刪除對(duì)象元素的操作,可通過(guò)del obj[key]來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyList:    def __delitem__(self, index):        del self.items[index]

8、__iter__(self): 迭代器

__iter__方法返回一個(gè)可迭代對(duì)象,通常與__next__方法一起使用,實(shí)現(xiàn)對(duì)象的迭代。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyList:    def __iter__(self):        self.index = 0        return self    def __next__(self):        if self.index < len(self.items):            result = self.items[self.index]            self.index += 1            return result        else:            raise StopIteration

9、__next__(self): 下一個(gè)迭代值

__next__方法用于返回迭代器的下一個(gè)值,通常與__iter__方法一起使用,可在循環(huán)中調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

10、__contains__(self, item): 包含性檢查

__contains__方法用于判斷對(duì)象是否包含某個(gè)元素,可通過(guò)item in obj來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyList:    def __contains__(self, item):        return item in self.items

11、__eq__(self, other): 相等性比較

__eq__方法定義了對(duì)象的相等性比較,可通過(guò)obj == other來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class Point:    def __eq__(self, other):        return self.x == other.x and self.y == other.y

12、__ne__(self, other): 不相等性比較

__ne__方法定義了對(duì)象的不相等性比較,可通過(guò)obj != other來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

13、__lt__(self, other): 小于比較

__lt__方法定義了對(duì)象的小于比較,可通過(guò)obj < other來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

14、__le__(self, other): 小于等于比較

__le__方法定義了對(duì)象的小于等于比較,可通過(guò)obj <= other來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

15、__gt__(self, other): 大于比較

__gt__方法定義了對(duì)象的大于比較,可通過(guò)obj > other來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

16、__ge__(self, other): 大于等于比較

__ge__方法定義了對(duì)象的大于等于比較,可通過(guò)obj >= other來(lái)調(diào)用。cdl28資訊網(wǎng)——每日最新資訊28at.com

這些特殊方法允許自定義類的行為,使其能夠按照需求進(jìn)行構(gòu)建和交互。通過(guò)覆蓋這些方法,可以實(shí)現(xiàn)更高級(jí)的功能,例如自定義容器類、實(shí)現(xiàn)迭代器、支持比較操作等。cdl28資訊網(wǎng)——每日最新資訊28at.com

特殊屬性(Magic Attributes)

1、__doc__: 文檔字符串

__doc__屬性包含類或函數(shù)的文檔字符串,可以通過(guò)obj.__doc__來(lái)訪問(wèn)。這對(duì)于文檔和注釋非常有用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyClass:    """這是我的類的文檔字符串。"""print(MyClass.__doc__)

2、__class__: 類

__class__屬性包含對(duì)象所屬的類,可以通過(guò)obj.__class__來(lái)訪問(wèn)。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyClass:    passobj = MyClass()print(obj.__class__)

3、__name__: 模塊

名稱:cdl28資訊網(wǎng)——每日最新資訊28at.com

__name__屬性包含模塊的名稱,對(duì)于模塊級(jí)別的代碼有用。cdl28資訊網(wǎng)——每日最新資訊28at.com

if __name__ == "__main__":    print("This code is executed only when the script is run directly.")

4、__file__: 模塊文件路徑

__file__屬性包含模塊的文件路徑,對(duì)于模塊級(jí)別的代碼有用。cdl28資訊網(wǎng)——每日最新資訊28at.com

print(__file__)

5、__dict__: 屬性字典

__dict__屬性包含對(duì)象的屬性和方法的字典。可以動(dòng)態(tài)地添加、修改或刪除對(duì)象的屬性。cdl28資訊網(wǎng)——每日最新資訊28at.com

class Person:    passperson = Person()person.name = "Alice"person.age = 30print(person.__dict__)

6、__dir__(): 屬性和方法列表

__dir__()方法返回對(duì)象的屬性和方法的列表,可以通過(guò)dir(obj)來(lái)調(diào)用。這對(duì)于查看對(duì)象的可用成員非常有用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyClass:    def my_method(self):        passprint(dir(MyClass()))

7、__slots__: 屬性限制

__slots__屬性允許限制類的屬性,使其只能包含指定的屬性,從而節(jié)省內(nèi)存。這在需要?jiǎng)?chuàng)建大量對(duì)象時(shí)很有用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class MyObject:    __slots__ = ('name', 'age')obj = MyObject()obj.name = "Alice"obj.age = 30obj.address = "123 Main St."  # 會(huì)引發(fā)異常,因?yàn)?address'不在__slots__中

8、__bases__: 直接父類元組

__bases__屬性包含類的直接父類的元組,通常在類繼承和多重繼承時(shí)使用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class Parent1:    passclass Parent2:    passclass Child(Parent1, Parent2):    passprint(Child.__bases__)  # 輸出 (<class '__main__.Parent1'>, <class '__main__.Parent2'>)

9、__subclasses__(): 子類列表

__subclasses__()方法返回類的所有直接子類,通常與issubclass()函數(shù)一起使用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class Parent:    passclass Child1(Parent):    passclass Child2(Parent):    passprint(Parent.__subclasses__())  # 輸出 [<class '__main__.Child1'>, <class '__main__.Child2'>]

10、__mro__: 方法解析順序

__mro__屬性包含類的方法解析順序元組(Method Resolution Order),通常在多重繼承中查找方法時(shí)使用。cdl28資訊網(wǎng)——每日最新資訊28at.com

class A:    def foo(self):        passclass B(A):    def foo(self):        passclass C(A):    def foo(self):        passclass D(B, C):    passprint(D.__mro__)  # 輸出 (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

總結(jié)

特殊方法和屬性是Python中強(qiáng)大而靈活的工具,用于自定義類和對(duì)象的行為。cdl28資訊網(wǎng)——每日最新資訊28at.com

通過(guò)使用這些特殊方法和屬性,可以實(shí)現(xiàn)自定義的構(gòu)造函數(shù)、字符串表示、比較操作、迭代器等功能。特殊屬性則能夠訪問(wèn)與類和模塊相關(guān)的元數(shù)據(jù)信息。cdl28資訊網(wǎng)——每日最新資訊28at.com

理解并靈活運(yùn)用這些特殊方法和屬性能夠更好地定制和控制Python代碼,使其適應(yīng)各種需求和場(chǎng)景。cdl28資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-17891-0.htmlPython中的雙下劃線:特殊方法和屬性的魔法世界!

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com

上一篇: As Const:一個(gè)被低估的 TypeScript 特性

下一篇: Springboot內(nèi)置的工具類之ObjectUtils

標(biāo)簽:
  • 熱門(mén)焦點(diǎn)
Top 主站蜘蛛池模板: 方山县| 紫云| 永德县| 屏东市| 望城县| 苍梧县| 广平县| 德昌县| 漳州市| 肃北| 平阳县| 萨嘎县| 五常市| 新郑市| 万山特区| 卢湾区| 灵川县| 呈贡县| 雷州市| 蒲江县| 江津市| 易门县| 普定县| 玉林市| 双牌县| 恩施市| 磐安县| 锦州市| 宜良县| 青田县| 卢龙县| 大方县| 永定县| 锦州市| 台山市| 达日县| 孝义市| 雅安市| 施甸县| 高陵县| 邮箱|