Python3 6內建函式 5 bin

2021-08-14 14:43:35 字數 1808 閱讀 4014

bin(x)

convert an integer number to a binary string. the result is a valid python expression. if x is not a python int object, it has to define an __index__() method that returns an integer.

1、將乙個整型數字轉換成二進位制字串

>>> a = bin(1)

>>> a

'0b1'

>>> type(a)    #獲取a的型別

2、如果引數x不是乙個整數,則x必須定義乙個 __index__() 方法,並且方法返回值必須是整數。

下面來看一下詳細**說明:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

#2.1 如果物件不是整數,則報錯

>>>

class a

():

pass

>>> a

= a(

)>>> bin(a)

traceback

(most recent call last

):file

"", line

1,in

>

bin (a

)typeerror:

'a'object cannot be interpreted

as an integer

#2.2 如果物件定義了__index__方法,但返回值不是整數,報錯

>>>

class a

():

def __index__

(self

):

return

"1">>> b

= a(

)>>> bin(b)

traceback

(most recent call last

):file

"", line

1,in

>

bin (b

)typeerror: __index__ returned non-

int(type

str)

#2.3 物件定義了__index__方法,且返回值是整數,將__index__方法返回值轉換成二進位制字串

>>>

class a

():

def __index__

(self

):

return

1>>> c

= a(

)>>> bin(c)

'0b1'

python3 6中內建函式變化

最近學習發現,python3.x比之與python2.x,許多內建要麼不再是內建函式,要麼已經改變呼叫方式。因此決定把已知的變化寫下,以作參考。目前reduce函式已經移到functools模組中,呼叫前需要先導入functools模組 import functools functools.redu...

Python內建函式 36 reversed

英文文件 reversed seq return a reverse iterator.seq must be an object which has a reversed method or supports the sequence protocol the len method and the...

Python基礎學習 內建函式(5)

41.max iterable,key,default max arg1,arg2,args key 該函式返回iterable引數 必須是可迭代的 內最大的元素,或者給出所有引數中最大的元素。key引數與default是可選的關鍵字引數。key引數必須是單引數排序函式 如果iterable引數為空...