簡體   English   中英

python是否內置了類型值?

[英]Does python have built in type values?

不是拼寫錯誤。 我的意思是類型值。 類型的值是'type'。

我想寫一個問題要問:

if type(f) is a function : do_something()

我是否需要創建臨時功能並執行:

if type(f) == type(any_function_name_here) : do_something()

或者是我可以使用的內置類型類型集? 像這樣:

if type(f) == functionT : do_something()

對於通常要檢查的功能

>>> callable(lambda: 0)
True

尊重鴨子打字。 但是有types模塊:

>>> import types
>>> dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__']

但是,您不應該檢查type相等,而是使用isinstance

>>> isinstance(lambda: 0, types.LambdaType)
True

確定變量是否為函數的最佳方法是使用inspect.isfunction 一旦確定變量是函數,就可以使用.__name__屬性來確定函數的名稱並執行必要的檢查。

例如:

import inspect

def helloworld():
    print "That famous phrase."

h = helloworld

print "IsFunction: %s" % inspect.isfunction(h)
print "h: %s" % h.__name__
print "helloworld: %s" % helloworld.__name__

結果:

IsFunction: True
h: helloworld
helloworld: helloworld

isfunction是標識函數的首選方法,因為類中的方法也是callable

import inspect

class HelloWorld(object):
    def sayhello(self):
        print "Hello."

x = HelloWorld()
print "IsFunction: %s" % inspect.isfunction(x.sayhello)
print "Is callable: %s" % callable(x.sayhello)
print "Type: %s" % type(x.sayhello)

結果:

IsFunction: False
Is callable: True
Type: <type 'instancemethod'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM