python有内置的类型值吗?

2024-09-29 22:00:55 发布

您现在位置:Python中文网/ 问答频道 /正文

不是打字错误。我是说类型值。值的类型是“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()

Tags: 函数name类型ifhereistype错误
2条回答

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

对于您通常会检查的功能

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

相关问题 更多 >

    热门问题