python - __call__ 来自 __init__ 的元类阴影签名

标签 python spyder metaclass

我想在下面的代码中输入 instance_of_A = A( 时,假定参数的名称是 init_argumentA 而不是 *meta_args, **meta_kwargs 。但不幸的是,显示了元类的 __call__ 方法的参数。

class Meta(type):    
    def __call__(cls,*meta_args,**meta_kwargs):
        # Something here
        return super().__call__(*meta_args, **meta_kwargs)

class A(metaclass = Meta):
    def __init__(self,init_argumentA):
        # something here 

class B(metaclass = Meta):
    def __init__(self,init_argumentB):
        # something here

我搜索了一个解决方案,发现了问题 How to dynamically change signatures of method in subclass? Signature-changing decorator: properly documenting additional argument 。但没有,似乎完全是我想要的。第一个链接使用检查来更改赋予函数的变量数量,但我似乎无法让它适用于我的情况,我认为必须有一个更明显的解决方案。
第二个并不完全是我想要的,但这种方式可能是一个不错的选择。

编辑:我在 Spyder 工作。我想要这个是因为我有数千个 Meta 类型的类,每个类都有不同的参数,这是不可能记住的,所以这个想法是当用户看到正确的参数出现时可以记住它。

最佳答案

使用您提供的代码,您可以更改 Meta类(class)

class Meta(type):
    def __call__(cls, *meta_args, **meta_kwargs):
        # Something here
        return super().__call__(*meta_args, **meta_kwargs)


class A(metaclass=Meta):
    def __init__(self, x):
        pass



import inspect

class Meta(type):
    def __call__(cls, *meta_args, **meta_kwargs):
        # Something here

        # Restore the signature of __init__
        sig = inspect.signature(cls.__init__)
        parameters = tuple(sig.parameters.values())
        cls.__signature__ = sig.replace(parameters=parameters[1:])

        return super().__call__(*meta_args, **meta_kwargs)

现在 IPython 或某些 IDE 将向您显示正确的签名。

关于python - __call__ 来自 __init__ 的元类阴影签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740290/

相关文章:

python - 在 ParaView 中通过 Python 脚本保存动画

python - Django Rest Framework - 在列表中获取完整的相关对象

python - 如何将多个项目 append 到 pandas df?

python-3.x - 如何在 Spyder 上更新 Python 版本?

windows - Anaconda Spyder 4.1.5 更新

python - Plotly:如何在 Spyder 中显示图表?

c++ - 枚举QQmlEngine中的所有对象

python - 大型 csv 文件的转置

python-3.x - 具有指定元类的 Python abc 继承

python - 用模拟对象替换类的元类