打字模块中的什么类型描述了一个类?什么类型描述了一个函数? [英] What type in the typing module describes a class? What type describes a function?

查看:46
本文介绍了打字模块中的什么类型描述了一个类?什么类型描述了一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The new typing module in Python 3.5 provides a number of tools for use in type annotations. Does it provide an object or type that encapsulates the idea of class? How about the idea of function?

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

In the following code, which defines a decorator, what should stand in for class_? What should stand in for function? (typing.Callable is inadequate, because for example a class is callable, but the code is trying to identify methods.) (The no_type_check() decorator in the typing module itself might be a prototype for decorators that act like this. no_type_check() itself does not have any annotations, type-hint or otherwise.)

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

推荐答案

类是 type 类型的实例.

函数属于 types.FunctionTypetypes.BuiltinFunctionType 类型.

Functions are of the types types.FunctionType or types.BuiltinFunctionType.

方法属于 types.MethodTypetypes.BuiltinMethodType 类型.

Methods are of the types types.MethodType or types.BuiltinMethodType.

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

types has been a part of Python for... a very long time.

这篇关于打字模块中的什么类型描述了一个类?什么类型描述了一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆