gpt4 book ai didi

python - 如何动态更改子类中方法的签名?

转载 作者:太空宇宙 更新时间:2023-11-03 14:55:16 24 4
gpt4 key购买 nike

使用classmethod动态改变子类中的方法时,如何动态改变方法的签名?

示例

import inspect

class ModelBase(object):

@classmethod
def method_one(cls, *args):
raise NotImplementedError

@classmethod
def method_two(cls, *args):
return cls.method_one(*args) + 1

class SubClass(ModelBase):
@staticmethod
def method_one(a, b):
return a + b

test = SubClass()

try:
print(inspect.signature(test.method_two))
except AttributeError:
print(inspect.getargspec(test.method_two).args)

我想要 test.method_two 获取 test.method_one 的签名。如何重写父类ModelBase

我读过Preserving signatures of decorated functions 。在 python3.4+ 中,functools.wraps 有助于保留修饰函数的签名。我想将它应用到类方法中。

当使用functools.wraps时,我需要指定装饰方法的名称。但是在这种情况下如何访问 classmethod 之外的修饰方法呢?

from functools import wraps

class ModelBase(object):

@classmethod
def method_one(cls, *args):
raise NotImplementedError

@classmethod
def method_two(cls):
@wraps(cls.method_one)
def fun(*args):
return cls.method_one(*args) + 1
return fun

method_two 返回一个包装函数,但我必须将它与 test.method_two()(*arg) 一起使用。这个方法不是直接的。

最佳答案

如果这仅用于自省(introspection)目的,您可以覆盖 ModelBase 上的 __getattribute__ ,每次访问 method_two 时,我们都会返回一个具有以下功能的函数: method_one 的签名。

import inspect

def copy_signature(frm, to):
def wrapper(*args, **kwargs):
return to(*args, **kwargs)
wrapper.__signature__ = inspect.signature(frm)
return wrapper


class ModelBase(object):

@classmethod
def method_one(cls, *args):
raise NotImplementedError

@classmethod
def method_two(cls, *args):
return cls.method_one(*args) + 1

def __getattribute__(self, attr):
value = object.__getattribute__(self, attr)
if attr == 'method_two':
value = copy_signature(frm=self.method_one, to=value)
return value


class SubClass(ModelBase):
@staticmethod
def method_one(a, b):
return a + b


class SubClass2(ModelBase):
@staticmethod
def method_one(a, b, c, *arg):
return a + b

演示:

>>> test1 = SubClass()
>>> print(inspect.signature(test1.method_two))
(a, b)
>>> test2 = SubClass2()
>>> print(inspect.signature(test2.method_two))
(a, b, c, *arg)

关于python - 如何动态更改子类中方法的签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45626647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com