不是打错了,我指的是类型值。类型为'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'>
type(f) == type(any_function_name_here)
没有什么特别之处,它只是比较某个函数调用产生的两个值。 - user395760