打字模块中的什么类型描述了 class?什么类型描述了一个函数?
What type in the typing module describes a class? What type describes a function?
Python 3.5 中的新 typing
模块提供了许多用于类型注释的工具。它是否提供了封装了 class 思想的对象或类型? function的想法怎么样?
在下面定义装饰器的代码中,class_
应该用什么表示? function
应该代表什么? (typing.Callable
是不够的,因为例如 class 是可调用的,但代码试图识别方法。)(typing
模块本身中的 no_type_check()
装饰器可能是像这样的装饰器的原型。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
类 是类型 type
的实例。
函数的类型为 types.FunctionType
或 types.BuiltinFunctionType
。
方法属于 types.MethodType
或 types.BuiltinMethodType
类型。
types
已经成为 Python 的一部分……很长一段时间了。
Python 3.5 中的新 typing
模块提供了许多用于类型注释的工具。它是否提供了封装了 class 思想的对象或类型? function的想法怎么样?
在下面定义装饰器的代码中,class_
应该用什么表示? function
应该代表什么? (typing.Callable
是不够的,因为例如 class 是可调用的,但代码试图识别方法。)(typing
模块本身中的 no_type_check()
装饰器可能是像这样的装饰器的原型。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
类 是类型 type
的实例。
函数的类型为 types.FunctionType
或 types.BuiltinFunctionType
。
方法属于 types.MethodType
或 types.BuiltinMethodType
类型。
types
已经成为 Python 的一部分……很长一段时间了。