本文討論python中將某個復雜對象轉換為簡單對象或數據類型的常用魔術放啊,這些在編程中是十分有用的。
1、__str__
方法。
在講解本方法前我們先打開一個jupyter notebook,隨意創建一個類如下,使用str()方法輸出該類的實例看看返回了什么:
1
2
3
4
5
6
7
8
9
|
class BarChart( object ): def __init__( self , x, y, labels,color): self .x = x self .y = y self .labels = labels self .color = color def show( self ): pass str (BarChart(x = [ 1 , 2 , 3 ,], y = [ 10 , 30 , 20 ],labels = [ '1' , '2' , '3' ])) |
Out[1]:
‘<main.BarChart object at 0x0000017B5704D5B0>'
日常開發中,多數情況下,形如<main.BarChart object at 0x0000017B5704D5B0>這樣的輸出對我們沒有任何作用。然而在python中卻常用str()方法進行強制類型轉換,我們希望將某個對象轉換成字符串后是某一定的意義的,這就需要用到魔術方法__str__
。__str__
方法在對象傳遞給str的構造函數時被調用;該方法接受一個位置參數(self),具體請看下例:
1
2
3
4
5
6
7
8
9
10
11
|
class BarChart( object ): def __init__( self , x, y, labels, color): self .x = x self .y = y self .labels = labels self .color = color def show( self ): pass def __str__( self ): return '我是一個bar圖,我的顏色值為:' + self .color str (BarChart(x = [ 1 , 2 , 3 ,], y = [ 10 , 30 , 20 ],labels = [ '1' , '2' , '3' ],color = 'red' )) |
Out[2]:
‘我是一個bar圖,我的顏色值為:red'
2.__unicode__
方法和__bytes__
方法
python2中的字符串是ASCII字符串,而python3中采用的是Unicode字符串,并且python3還引入了bytes(bytestring)類型。不同的字符串家族擁有自己的魔術方法:
-
python2中出品了
__unicode__
魔術方法,該方法在對象傳遞給unicode的構造函數時被調用,接受一個位置參數(self); -
python3中出品了
__bytes__
魔術方法,該方法在對象傳遞給bytes的構造函數時被調用,接受一個位置參數(self);
3.__bool__
方法
其實道理也是類似的,__bool__
在對象傳遞給bool的構造函數時被調用。但是在python2和python3中對于該方法的命名不一樣:
-
在python2中被命名為
__nonzero__
方法; -
在python3中被命名為
__bool__
方法。
不過,兩者的功能是一致的,它們都接受一個位置參數(self)并返回一個bool值,即True
或False
。
4.__int__
、__float__
和__complex__
方法
如果一個對象定義了一個返回int類型的__int__
方法,那么該對象被傳遞給int的構造函數時,int方法會被調用。類似地,若對象定義了__float__
方法和__complex__
方法 ,也會在各自傳遞給float或complex的構造函數時被調用。另外,python2中擁有Long類型(而python3中不再擁有),因此在python2中相應地有__long__
方法。
到此這篇關于Python類型轉換的魔術方法的文章就介紹到這了,更多相關Python類型轉換魔術方法內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_28550263/article/details/111506439