types.MethodType
所期望的参数是什么?它会返回什么?https://docs.python.org/3.6/library/types.html没有说更多关于它的内容:
types.MethodType 用户定义的类实例的方法类型。
举个例子,来自https://docs.python.org/3.6/howto/descriptor.html
为了支持方法调用,函数包括用于在属性访问期间绑定方法的
__get__()
方法。这意味着所有函数都是非数据描述符,它们返回绑定方法或非绑定方法,这取决于它们是从对象还是从类调用的。在纯python中,它的工作方式如下: 类函数(对象):。。def __get__( self,obj,objtype=None):“在对象/funcobject.c中模拟func_descr_get()”,如果obj为None:返回自返回types.MethodType(self,obj)
self
of types.MethodType
必须是可调用对象吗?换句话说,类Function
必须是可调用类型,即Function
必须有一个方法__call__
。self
是一个可调用的对象,那么它至少需要一个参数吗?types.MethodType(self, obj)
是否意味着将obj
作为可调用对象self
的第一个参数,即将self
与obj
一起运行?types.MethodType(self, obj)
如何创建和返回types.MethodType
实例谢谢。
发布于 2021-07-19 15:03:43
文档并不多,但是您可以始终检查它的源代码。MethodType构造函数的签名是:
def __init__(self, func: Callable[..., Any], obj: object) -> None: ...
它接受可调用的对象,并返回None。
可以使用MethodType将实例方法添加到对象,而不是函数;下面是一个示例:
from types import MethodType
class MyClass:
language = 'Python'
# a function is bound to obj1
obj1 = MyClass()
obj1.say_hello = lambda: 'Hello World!'
print(type(obj1.say_hello)) # type is class 'function'
obj1.say_hello()
# a method is bound to obj2
obj2 = MyClass()
# this is used to bind a "method" to a specific object obj2, rather than a function
obj2.say_hello = MethodType(lambda self: f'Hello {self.language}!', obj2)
print(type(obj2.say_hello)) # type is class 'method'
obj2.say_hello()
https://stackoverflow.com/questions/46525069
复制相似问题