2024-09-29 22:00:55 发布
网友
不是打字错误。我是说类型值。值的类型是“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()
确定变量是否为函数的最佳方法是使用inspect.isfunction。一旦确定变量是函数,就可以使用.__name__属性来确定函数的名称并执行必要的检查。你知道吗
.__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:
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'>
对于您通常会检查的功能
>>> callable(lambda: 0) True
尊重鸭子打字。但是有types模块:
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
type
isinstance
>>> isinstance(lambda: 0, types.LambdaType) True
确定变量是否为函数的最佳方法是使用inspect.isfunction。一旦确定变量是函数,就可以使用
.__name__
属性来确定函数的名称并执行必要的检查。你知道吗例如:
结果是:
isfunction
是标识函数的首选方法,因为类中的方法也是callable
:结果是:
对于您通常会检查的功能
尊重鸭子打字。但是有
types
模块:但是您不应该检查
type
相等,而是使用isinstance
相关问题 更多 >
编程相关推荐