打字模块中的哪个类型描述了一个类?什么类型描述功能?

时间:2015-12-24 23:41:48

标签: python python-3.x types python-3.5 python-typing

Python 3.5中的新typing模块提供了许多用于类型注释的工具。它是否提供了封装 class 概念的对象或类型? 功能的想法怎么样?

在下面的定义装饰器的代码中,class_应该代表什么? function应该代表什么? (typing.Callable是不合适的,因为例如一个类是可调用的,但是代码正试图识别方法。)(no_type_check()模块中的typing装饰器本身可能是装饰器的原型这样做。no_type_check()本身没有任何注释,类型提示或其他。)

import typing

def is_double_underscore_name (name):
    return len(name) > 4 and name.startswith('__') and name.endswith('__')

# This code will not run, because 'class_' and 'function' are names that do not have any
# predefined meaning. See the text of the question.

# Note: This modifies classes in-place but (probably) does not modify functions in-place;
# this is not a considered design decision; it is just the easiest thing to do in a very
# basic example like this.
def do_something (class_or_function: typing.Union[class_, function]):
    if isinstance(class_or_function, class_):
        for name in class_or_function.__dict__:
            if not is_double_underscore_name(name):
                object = class_or_function.__dict__[name]
                if isinstance(object, function):
                    class_or_function.__dict__[name] = do_something(object)
        return class_or_function
    else:
        ... # return the function, modified in some way

1 个答案:

答案 0 :(得分:3)

类是type类型的实例。

功能属于types.FunctionTypetypes.BuiltinFunctionType类型。

方法的类型为types.MethodTypetypes.BuiltinMethodType

types已经成为Python的一部分......很长一段时间。