python是否内置了类型值?

use*_*956 4 python types

不是拼写错误.我的意思是类型值.类型的值是'type'.

我想写一个问题要问:

if type(f) is a function : do_something()
Run Code Online (Sandbox Code Playgroud)

我是否需要创建临时功能并执行:

if type(f) == type(any_function_name_here) : do_something()
Run Code Online (Sandbox Code Playgroud)

或者是我可以使用的内置类型类型集?像这样:

if type(f) == functionT : do_something()
Run Code Online (Sandbox Code Playgroud)

jam*_*lak 7

对于通常要检查的功能

>>> callable(lambda: 0)
True
Run Code Online (Sandbox Code Playgroud)

尊重鸭子打字.但是有一个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__']
Run Code Online (Sandbox Code Playgroud)

但是,您不应该检查type相等性,而是使用isinstance

>>> isinstance(lambda: 0, types.LambdaType)
True
Run Code Online (Sandbox Code Playgroud)


mar*_*seu 6

确定变量是否为函数的最佳方法是使用inspect.isfunction.一旦确定变量是函数,就可以使用.__name__attribute来确定函数的名称并执行必要的检查.

例如:

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__
Run Code Online (Sandbox Code Playgroud)

结果:

IsFunction: True
h: helloworld
helloworld: helloworld
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

结果:

IsFunction: False
Is callable: True
Type: <type 'instancemethod'>
Run Code Online (Sandbox Code Playgroud)