[英]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.