Python是否有内置类型值?

4

不是打错了,我指的是类型值。类型为'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()

回答标题中的问题:是的,类是一等值。您可以将它们绑定到变量,运行时创建新类,传递它们等等。- type(f) == type(any_function_name_here) 没有什么特别之处,它只是比较某个函数调用产生的两个值。 - user395760
2个回答

7

对于您通常要检查的函数

>>> 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

6

判断变量是否为函数的最佳方法是使用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'>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接