Python3中内置函数callable介绍
生活随笔
收集整理的這篇文章主要介紹了
Python3中内置函数callable介绍
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? Python3中的內置函數callable接受一個對象參數,如果此對象參數看起來可調用,則callable函數返回True,否則返回False。如果返回True,則調用仍有可能失敗;但如果返回False,則調用對象將永遠不會成功。
? ? ? 類是可調用的(調用類會返回一個新實例),如果它們的類具有__call__方法,則實例是可調用的。
? ? ? 可以使用()運算符調用的任何(或任何對象)都稱為可調用對象。
? ? ? 在Python3中,一切都是對象,如函數、方法甚至類。
? ? ? 所有內置函數都是可調用的。
? ? ? 所有用戶定義的函數也是可調用的。
? ? ? lambda函數也是可調用的。
? ? ? 用戶定義的類也是可調用的。
? ? ? 所有內置方法也是可調用的,如list類包含insert,remove等內置方法,同樣,int, float等也都有自己的方法。
? ? ? 以下為測試代碼:
var = 2
if var == 1:# reference: https://www.geeksforgeeks.org/callable-in-python/def Geek():return 5# an object is created of Geek()let = Geek; print(callable(let)) # Truelet2 = Geek(); print(callable(let2)) # False# a test variablenum = 5 * 5; print(callable(num)) # Falseclass Geek2:def __call__(self):print('Hello GeeksforGeeks 2')# Suggests that the Geek2 class is callableprint(callable(Geek2)) # True# This proves that class is callableGeekObject2 = Geek2()# an instance of a class with a __call__ methodGeekObject2() # this is calling the __call__ method, Hello GeeksforGeeks 2class Geek3:def testFunc(self):print('Hello GeeksforGeeks 3')# Suggests that the Geek3 class is callableprint(callable(Geek3)) # True# the Geek3 class is callable, but the instance of Geek3 is not callable() and it returns a runtime errorGeekObject3 = Geek3()# The object will be created but returns an error on callingGeekObject3() # TypeError: 'Geek3' object is not callable
elif var == 2:# reference: https://pythonsimplified.com/what-is-a-callable-in-python/# 內置函數也是函數,因此它們也是可調用的,即callable()返回True. 所有的內置函數都是可調用的print(callable(min)) # Trueprint(callable(max)) # Trueprint(callable(print)) # Trueprint(callable(int)) # True, int classprint(callable(float)) # True, float classprint(callable(str)) # True, str classprint(callable(list)) # True, list class# 所有用戶定義的函數也是可調用的def hello(user):print(f"Welcome to Python Simplified, {user}")print(callable(hello)) # True# lambda函數也是可調用的print(callable(lambda x: x**2)) # True# 用戶定義的類也是可調用的class Rectangle:def __init__(self, width, height):self.height = heightself.width = widthdef area(self):return self.width * self.areaprint(callable(Rectangle)) # True# 所有內置方法也是可調用的my_list = [1,2,3,4,5]print(callable(my_list.append)) # Trueprint("test finish")
? ? ? GitHub:http://github.com/fengbingchun/Python_Test
總結
以上是生活随笔為你收集整理的Python3中内置函数callable介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3中lambda表达式介绍
- 下一篇: Python3中typing模块介绍