【问题标题】:What type in the typing module describes a class? What type describes a function?打字模块中的什么类型描述了一个类?什么类型描述了一个函数?
【发布时间】:2018-09-11 02:17:07
【问题描述】:

Python 3.5 中的新 typing 模块提供了许多用于类型注释的工具。是否提供了封装class思想的对象或类型? function的思路怎么样?

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

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

【问题讨论】:

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


    【解决方案1】:

    类是type 类型的实例。

    函数的类型为 types.FunctionTypetypes.BuiltinFunctionType

    方法的类型为types.MethodTypetypes.BuiltinMethodType

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

    【讨论】:

    • 是的,这并不新鲜。它在 3.5 中被淘汰了。 “纯粹胜于实用”是 3.x 的座右铭
    • @JürgenA.Erhard typesnot gutted in Python 3.5。不知道你从哪里得到的。
    • 从比较 2.7 到 3.5 的类型?希望所有问题都那么容易回答。
    • @JürgenA.Erhard: types 在 3.0 中进行了清理,主要删除了大量过时的名称。例如,types.IntType 已过时,因为 int 从工厂函数更改为实际 int 类型的名称。其他已删除的名称对应于不再存在的类型。我记得唯一不符合此模式的已删除名称是types.NoneType,但您可以使用type(None)
    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多