最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python?特殊屬性及方法詳細解析

 更新時間:2022年07月20日 17:11:06   作者:不負韶華?  
這篇文章主要介紹了python?特殊屬性及方法詳細解析,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下

概述

在python中,以單下劃線開頭的(_a)的代表不能直接訪問的類屬性,需通過類提供的接口進行訪問,不能用“from xxx import *”而導入,“單下劃線” 開始的成員變量叫做保護變量,意思是只有類對象和子類對象自己能訪問到這些變量;以雙下劃線開頭的(_ _a)代表類的私有成員,意思是只有類對象自己能訪問,連子類對象也不能訪問到這個數(shù)據(jù);以雙下劃線開頭和結(jié)尾的(_ _a_ _)代表python里特殊方法專用的標識,如 _ _init_ _()代表類的構造函數(shù)。

特殊屬性

1、 _ _ name _ _

如果是一個對象的調(diào)用,則表示類的名稱,而不是表示對象的名稱;如果當前模塊被直接執(zhí)行(主模塊),_ _ name _ _ 存儲的是_ _ main _ _ ;如果當前模塊是被調(diào)用的模塊(被導入),則_ _ name _ _存儲的是py文件名(模塊名稱)。

1、表示對象的名稱

>>> class A(object):
	a = 1
	def __init__(self):
		self.b = 'c'
>>> a = A()
>>> A.__name__
'A'
>>> a.__name__
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    a.__name__
AttributeError: 'A' object has no attribute '__name__'

2、表示_ _ main _ _函數(shù)的名稱,也就是程序的入口,類似于java中main函數(shù)

>>> __name__
'__main__'

3、如果當前模塊被其他模塊調(diào)用,則是當前模塊的名稱

demo1.py

print(__name__)

demo2.py

import demo1

運行demo2.py文件后,得到的結(jié)果為:

demo1

2、_ _ bases _ _ 和_ _ base _ _ 以及 _ _ mro _ _

_ _ bases _ _ 表示類的所有基類;_ _ base _ _ 輸出類繼承的第一個父類(類的基類); _ _ mro _ _ 輸出類的層次結(jié)構。

>>> class A:
    def __init__(self):
        self.a = 2

>>> class B(A):
    def __init__(self):
        super().__init__()
        self.b = 3

>>> class C(A):
    def __init__(self):
        super().__init__()
        self.c = 4

>>> class D(B, C):
    def __init__(self):
        super().__init__()
        self.d = 5

>>> D.__bases__
(<class '__main__.B'>, <class '__main__.C'>)
>>> D.__base__
<class '__main__.B'>
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

3、_ _ class _ _

表示對象的類型,相當于type()函數(shù)。

>>> class A:
	def __init__(self):
		self.a = 2

>>> a = A()
>>> a.__class__
<class '__main__.A'>

4、_ _ dict _ _

表示對象和類的一些屬性,用一個字典存儲起來。

>>> class A:
	a = 1
	b = 2
	def __init__(self):
		self.c = 3
		self.d = 4

>>> a = A()
>>> a.__dict__
{'c': 3, 'd': 4}
>>> A.__dict__
mappingproxy({'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function A.__init__ at 0x000001CD66F6B8B0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})

特殊方法

1、 _ _ subclasses _ _ ()

表示類的所有直接子類。

>>> class A:
	    def __init__(self):
	        self.a = 2

>>> class B(A):
	    def __init__(self):
	        super().__init__()
	        self.b = 3

>>> class C(A):
	    def __init__(self):
	        super().__init__()
	        self.c = 4

>>> class D(B, C):
	    def __init__(self):
	        super().__init__()
	        self.d = 5
        
>>> C.__subclasses__()
[<class '__main__.D'>]
>>> A.__subclasses__()
[<class '__main__.B'>, <class '__main__.C'>]

2、_ _ new _ _ ()、 _ _ init _ _ ()和 _ _ del _ _ ()

_ _ new _ _ ()是一個靜態(tài)方法,用于根據(jù)類型創(chuàng)建實例。Python在調(diào)用 _ _ new _ _ ()方法獲得實例后,會調(diào)用這個實例的_ _ init _ _ ()方法,然后將最初傳給 _ _ new _ _ ()方法的參數(shù)都傳給 _ _ init _ _ ()方法。

_ _ init _ _ ()是一個實例方法,用來在實例創(chuàng)建完成后進行必要的初始化,該方法必須返回None。Python不會自動調(diào)用父類的 _ _ init _ _ ()方法,這需要額外的調(diào)用:

super(C, self). _ _ init _ _ ()

_ _ new _ _ ()至少要有一個參數(shù)cls,代表要實例化的類,此參數(shù)在實例化時由Python解釋器自動提供;_ _ new _ _ ()必須要有返回值,返回實例化出來的實例,可以return父類new出來的實例,或直接是object的new出來的實例。

>>> class A(object):
		def __new__(cls, *args, **kwargs):
			print("__new__")
			instance = object.__new__(cls)
			# 或者
			# instance = super().__new__(cls)
			return instance
	
		def __init__(self):
			print("__init__")

>>> a = A()
__new__
__init__

在GC之前,Python會調(diào)用這個對象的 _ _ del _ _ ()方法完成一些終止化工作。如果沒有 _ _ del _ _ ()方法,那么Python不做特殊的處理;此外,Python無視_ _ del _ _ ()方法的返回值;Python不會自動調(diào)用父類的 _ _ del _ _ ()方法,除非顯式調(diào)用;定義了 _ _ del _ _ ()方法的實例無法參與到循環(huán)GC中,所以對于這樣的實例應該避免循環(huán)引用;try/finally語句或with語句可能是比_ _ del _ _()更好的方式。

>>> class A(object):
	    def __new__(cls, *args, **kwargs):
	        print("__new__")
	        instance = super().__new__(cls, *args, **kwargs)
	        return instance
	
	    def __init__(self):
	        print("__init__")
	
	    def __del__(self):
	        print("__del__")
	        
>>> a = A()
__new__
__init__
>>> del a
__del__

3、_ _ repr _ _ ()和 _ _ str _ _ ()

_ _ repr _ _ ()是一個 ”自我描述“ 的方法,也是Python類中的一個特殊方法,由object對象提供,由于object提供的這個 _ _ repr _ _ 方法總是返回一個對象, ( 類名 + obejct at + 內(nèi)存地址 ),這個值并不能真正實現(xiàn)自我描述的功能,如果你想在自定義類中實現(xiàn) “自我描述” 的功能,那么必須重寫 _ _ repr _ _ 方法。_ _ repr _ _ ()方法返回的字符串主要是面向解釋器的。

>>> class A(object):
	    def __repr__(self):
	        return "this is a class A"

>>> a = A()
>>> a
this is a class A
>>> print(a)
this is a class A
>>> str(a)
'this is a class A'

_ _ str _ _ ()與_ _ repr _ _ ()返回的詳盡的、準確的、無歧義的對象描述字符串不同,_ _ str _ _ ()方法只是返回一個對應對象的簡潔的字符串表達形式。如上代碼所示,當_ _ str _ _ ()缺失時,Python會調(diào)用_ _ repr _ _ ()方法。

>>> class A(object):
	    def __str__(self):
	        return "this is a class A"

>>> a = A()
>>> a
<__main__.A object at 0x000001CF8C8F9640>
>>> print(a)
this is a class A
>>> str(a)
'this is a class A'

實際上_ _ str _ _ ()只是覆蓋了_ _ repr _ _ ()以得到更友好的用戶顯示。Python內(nèi)置的str()函數(shù),print(x)語句,都會調(diào)用對象的_ _ str _ _()方法。

>>> class A(object):
    def __repr__(self):
        return "class A"
    
    def __str__(self):
        return "this is a class A"

>>> a = A()
>>> a
class A
>>> print(a)
this is a class A
>>> str(a)
'this is a class A'

4、_ _ call _ _ ()

定義了該方法的對象可以像函數(shù)那樣被調(diào)用,因此被稱為可調(diào)用對象。

>>> class A(object):
	    def __init__(self):
	        self.a = 2
	
	    def __call__(self, b, *args, **kwargs):
	        c = b + self.a
	        return c
>>> a = A()
>>> a(3)
5

5、_ _ lt _ _ ()、_ _ le _ _ ()、_ _ gt _ _ ()、_ _ ge _ _ ()、_ _ eq _ _ ()、_ _ ne _ _ ()

當兩個對象x、y分別進行x<y、x<=y、x>y、x>=y、x==y和x!=y運算時,會調(diào)用對應的函數(shù)。

>>> class A(object):
	    def __init__(self, b):
	        self.b = b
	
	    def __lt__(self, other):
	        print("__lt__")
	        return self.b < other.b

>>> c = A(3)
>>> d = A(4)
>>> c < d
__lt__
True

6、_ _ hash _ _ ()

三種情形會調(diào)用__hash__()方法:1. 內(nèi)置的hash()方法,2.作為字典的鍵時,3.作為集合的成員時;_ _ hash _ _ ()方法應該返回一個32位長的整數(shù),對與同一個對象,hash()方法應該總是返回相同的值;對于 x == y ,即使二者不屬于相同的類型,只要他們是可哈希的(hashable),都應該確保得到 hash(x) == hash(y) ;

>>> class A(object):
	    def __init__(self, n):
	        self.n = n
	
	    def __eq__(self, other):
	        return self.n == other.n
	
	    def __hash__(self):
	        return random.randint(0, 10)


>>> a = A(3)
>>> b = A(3)
>>> a == b
True
# 雖然a == b返回結(jié)果為True,但是hash(a)和hash(b)返回結(jié)果不一樣,所以不能說這兩個對象是相同的。
>>> hash(a)
3
>>> hash(b)
5

_ _ eq _ _()正確的用法:

class A(object):
	def __init__(self, n):
	    self.n = n
	        
	def __hash__(self):
        return hash(id(self))
        
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return hash(id(self))==hash(id(other))
        else:
            return False 

通過_ _ hash _ _ 返回一個int值,用來標記這個對象。對于類而言,如果沒有實現(xiàn)_ _ eq _ _ ()和 _ _ hash _ _ ()函數(shù),那么會自動繼承object._ _ hash _ _()。

到此這篇關于python 特殊屬性及方法詳細解析的文章就介紹到這了,更多相關python 屬性方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python基于DeepSeek大模型的提示詞優(yōu)化方案

    Python基于DeepSeek大模型的提示詞優(yōu)化方案

    以下基于DeepSeek大模型特性及搜索結(jié)果的綜合分析,結(jié)合提示詞設計原則、技術原理與優(yōu)化策略,提供完整Python代碼案例及詳細解析,需要的朋友可以參考下
    2025-04-04
  • 關于Pytorch的MLP模塊實現(xiàn)方式

    關于Pytorch的MLP模塊實現(xiàn)方式

    今天小編就為大家分享一篇關于Pytorch的MLP模塊實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • python簡單鼠標自動點擊某區(qū)域的實例

    python簡單鼠標自動點擊某區(qū)域的實例

    今天小編就為大家分享一篇python簡單鼠標自動點擊某區(qū)域的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-06-06
  • 詳解Python實現(xiàn)進度條的4種方式

    詳解Python實現(xiàn)進度條的4種方式

    這篇文章主要介紹了Python實現(xiàn)進度條的4種方式,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-01-01
  • Union在Python類型注解中的應用與最佳實踐

    Union在Python類型注解中的應用與最佳實踐

    Union” 在中文中通常翻譯為“聯(lián)合”,在數(shù)學和邏輯學中,它指的是兩個或多個集合的并集,在 Python 的類型注解中,Union 類型表示一個變量可以是多種類型中的任意一種,這與數(shù)學中的并集概念相似,本文介紹了Union在Python類型注解中的應用與最佳實踐
    2024-09-09
  • 深入理解Python虛擬機中浮點數(shù)(float)的實現(xiàn)原理及源碼

    深入理解Python虛擬機中浮點數(shù)(float)的實現(xiàn)原理及源碼

    在本篇文章當中主要分析在 cpython 虛擬機當中 float 類型的實現(xiàn)原理以及與他相關的一些源代碼,文中的示例代碼講解詳細,感興趣的可以了解一下
    2023-03-03
  • python任務調(diào)度實例分析

    python任務調(diào)度實例分析

    這篇文章主要介紹了python任務調(diào)度實現(xiàn)方法,實例分析了任務調(diào)度的原理與Python實現(xiàn)方法,需要的朋友可以參考下
    2015-05-05
  • python matplotlib.pyplot.plot()參數(shù)用法

    python matplotlib.pyplot.plot()參數(shù)用法

    這篇文章主要介紹了python matplotlib.pyplot.plot()參數(shù)用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • python不帶重復的全排列代碼

    python不帶重復的全排列代碼

    輸入起始數(shù)字和結(jié)束數(shù)字將數(shù)組全排列,需要的朋友可以參考下
    2013-08-08
  • python groupby函數(shù)實現(xiàn)分組后選取最值

    python groupby函數(shù)實現(xiàn)分組后選取最值

    這篇文章主要介紹了python groupby函數(shù)實現(xiàn)分組后選取最值,文章圍繞主題相關資料展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-06-06

最新評論

福州市| 军事| 乌拉特前旗| 靖远县| 汕尾市| 隆子县| 武定县| 柳州市| 台前县| 信丰县| 万山特区| 浪卡子县| 台湾省| 瑞金市| 梁河县| 新化县| 新和县| 遂平县| 波密县| 勐海县| 潼南县| 西乌| 百色市| 正宁县| 龙游县| 十堰市| 濮阳县| 玉林市| 闸北区| 逊克县| 扬州市| 冀州市| 宜兰县| 吴江市| 五寨县| 汝城县| 金山区| 民县| 响水县| 平南县| 汉中市|