1. 程式人生 > >Python標準內建函式(26-30)

Python標準內建函式(26-30)

1.26  函式globals()

在Python程式中,函式globals()的功能是以字典型別返回當前位置的全部全域性變數,也就是返回表示當前全域性符號表的字典。函式globals()總是當前模組的字典,在函式或者方法中,它是指定義的模組而不是呼叫的模組。

例如在下面的例項檔案glo.py中,演示了使用函式globals()返回全部全域性變數的過程。

print(globals())#沒有設定變數

a = 1

print(globals())#多了一個a

a='toppr'#多了一個toppr

print(globals()) # globals 函式返回一個全域性變數的字典,包括所有匯入的變數。

執行後會輸出:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002BCC9BDD048>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'glo.py', '__cached__': None}

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002BCC9BDD048>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'glo.py', '__cached__': None, 'a': 1}

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002BCC9BDD048>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'glo.py', '__cached__': None, 'a': 'toppr'}

在上述執行效果中,第一行是變數為空時的執行效果,在最後顯示為“None”。第二行是變數“a=1” 時的執行效果,在最後顯示為“'a': 1”。第三行是變數“a='toppr'” 時的執行效果,在最後顯示為“'a': 'toppr'”。

1.27  函式hasattr()

在Python程式中,函式hasattr()的功能是判斷在指定物件中是否包含對應的屬性。使用函式hasattr(object, name)的語法格式如下所示。

hasattr(object, name)
  1. object:物件。
  2. name:字串,表示屬性名。

如果字串name是物件的一個屬性則返回True,否則返回False。函式hasattr()實際上是呼叫getattr(object,name)函式,通過是否丟擲AttributeError來判斷是否含有屬性。例如在下面的例項檔案has.py中,演示了使用函式hasattr()判斷在指定物件中是否包含對應的屬性的過程。

# 定義類A

class Student:

    def __init__(self, name):

        self.name = name



s = Student('Aim')

print(hasattr(s, 'name'))           # a含有name屬性

print(hasattr(s, 'age'))            # a不含有age屬性



# 定義類Coordinate

class Coordinate:

    x = 10

    y = -5

    z = 0



point1 = Coordinate()

print(hasattr(point1, 'x'))  # 有該屬性

print(hasattr(point1, 'y'))  # 有該屬性

print(hasattr(point1, 'z'))  # 有該屬性

print(hasattr(point1, 'no')) # 沒有該屬性

執行後會輸出:

True

False

True

True

True

False

1.28  函式hash()

在Python程式中,函式hash()的功能是獲取取一個物件(字串或者數值等)的雜湊值。使用函式hash()的語法格式如下所示。

hash(object)

引數object是一個物件,返回的雜湊值是一個整數。雜湊值用於在查詢字典時快速地比較字典的鍵,相等數值的雜湊值相同(即使它們的型別不同,比如1和1.0)。例如在下面的例項檔案hash.py中,演示了使用函式hash()獲取取一個物件的雜湊值的過程。

print(hash('test'))            # 字串

print(hash(1))                 # 數字

print(hash(str([1,2,3])))      # 集合

print(hash(str(sorted({'1':1}))))# 字典

#相等的數值,即使型別不一致,計算的雜湊值是一樣的。

print(1.0 == 1)

print(hash(1.0))

print(hash(1))

print(hash(1.0000))

執行後會輸出:

749979671510942164

1

1217072518131548941

-8397379028218661641

True

1

1

1

1.29  函式help()

在Python程式中,使用函式help()的語法格式如下所示。

help([object])

函式help()的功能是呼叫內建的幫助系統,檢視object函式或模組用途的詳細說明。如果沒有引數object,在直譯器的控制檯啟動互動式幫助系統。如果引數object是一個字串,該字串被當作模組名、函式名、類名、方法名、關鍵字或者文件主題而被查詢,在控制檯上列印幫助頁面。如果引數object是其它型別的某種物件,則會生成關於物件的幫助頁面。例如下面演示了在直譯器互動介面使用無參函式help()的過程。

>>> help() #不帶引數



Welcome to Python 3.5's help utility!



If this is your first time using Python, you should definitely check out

the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.



Enter the name of any module, keyword, or topic to get help on writing

Python programs and using Python modules.  To quit this help utility and

return to the interpreter, just type "quit".



To get a list of available modules, keywords, symbols, or topics, type

"modules", "keywords", "symbols", or "topics".  Each module also comes

with a one-line summary of what it does; to list the modules whose name

or summary contain a given string such as "spam", type "modules spam".



#進入內建幫助系統  >>> 變成了 help>

help> str #str的幫助資訊

Help on class str in module builtins:



class str(object)

 |  str(object='') -> str

 |  str(bytes_or_buffer[, encoding[, errors]]) -> str

 | 

 |  Create a new string object from the given object. If encoding or

 |  errors is specified, then the object must expose a data buffer

 |  that will be decoded using the given encoding and error handler.

 |  Otherwise, returns the result of object.__str__() (if defined)

 |  or repr(object).

 |  encoding defaults to sys.getdefaultencoding().

 |  errors defaults to 'strict'.

 | 

 |  Methods defined here:

 | 

 |  __add__(self, value, /)

 |      Return self+value.

 ................................





help> 1 #不存在的模組名、類名、函式名

No Python documentation found for '1'.

Use help() to get the interactive help utility.

Use help(str) for help on the str class.



help> quit #退出內建幫助系統



You are now leaving help and returning to the Python interpreter.

If you want to ask for help on a particular object directly from the

interpreter, you can type "help(object)".  Executing "help('string')"

has the same effect as typing a particular string at the help> prompt.



# 已退出內建幫助系統,返回互動介面 help> 變成 >>>

>>>

當在直譯器互動介面傳入引數呼叫函式時,將查詢引數是否是模組名、類名、函式名,如果則將顯示其使用說明。例如下面演示了在直譯器互動介面使用有參函式help()的過程。

>>> help(str)

Help on class str in module builtins:



class str(object)

 |  str(object='') -> str

 |  str(bytes_or_buffer[, encoding[, errors]]) -> str

 | 

 |  Create a new string object from the given object. If encoding or

 |  errors is specified, then the object must expose a data buffer

 |  that will be decoded using the given encoding and error handler.

 |  Otherwise, returns the result of object.__str__() (if defined)

 |  or repr(object).

 |  encoding defaults to sys.getdefaultencoding().

 |  errors defaults to 'strict'.

 | 

 |  Methods defined here:

 | 

 |  __add__(self, value, /)

 |      Return self+value.

 | 

  ***************************

例如在下面的例項檔案help.py中,演示了使用函式help()獲取幫助資訊的過程。

print(help('sys'))# 檢視 sys 模組的幫助

print(help('str'))# 檢視 str 資料型別的幫助



a = [1, 2, 3]

print(help(a))# 檢視列表 list 幫助資訊

print(help(a.append))# 顯示list的append方法的幫助

執行後的效果如圖1-1所示。

圖1-1  執行效果

1.30  函式hex()

在Python程式中,使用函式hex()的語法格式如下所示。

hex(x)

函式hex()的功能是將10進位制整數轉換成16進位制,以字串形式表示。引數x是一個10進位制整數。如果引數x不是Python int物件,則必須定義一個__index__()方法,返回一個整數。讀者需要注意的是,如果要獲取浮點型的十六進位制字串表示形式,需要使用float.hex()方法實現。例如在下面的例項檔案hex.py中,演示了用函式hex()將10進位制整數轉換成16進位制整數的過程。

#將10進位制整數轉換成16進位制整數。

print(hex(15))

print(hex(16))

# 未定義__index__函式

class Student:

    def __init__(self,name,age):

        self.name = name

        self.age = age



s = Student('Kim',10)

①print(hex(s))

在上述程式碼中,①處的s不是一個人整數,所以執行後會輸出錯誤資訊:

0xf

Traceback (most recent call last):

0x10

  File "hex.py", line 12, in <module>

    print(hex(s))

TypeError: 'Student' object cannot be interpreted as an integer

例如在下面的例項檔案hex1.py中,演示了用函式hex()轉換非整數的過程。

#定義__index__函式,並返回整數

class Student:

    def __init__(self,name,age):

        self.name = name

        self.age = age

    def __index__(self):

        return self.age



s = Student('Kim',10)

print(hex(s))



#定義__index__函式,但是返回字串

class Student:

    def __init__(self,name,age):

        self.name = name

        self.age = age

    def __index__(self):

        return self.name #返回的是name,不是整數



s = Student('Kim',10)

print(hex(s))

執行後會輸出:

0xa

Traceback (most recent call last):

  File "hex1.py", line 21, in <module>

    print(hex(s))

TypeError: __index__ returned non-int (type str)