Python Decorator / Class方法和Pycharm

问题描述 投票:0回答:1

为什么装饰的方法没有显示在NextTip(Pycharm)中

from functools import wraps

def add_method(cls):
    def decorator(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            return func(self, *args, **kwargs)
        setattr(cls, func.__name__, wrapper)
        return func
    return decorator
class Apple():
    def __init__(self):
        print("my apple")
    def appletest(self):
        print("apple test")
@add_method(Apple)
def mangotest(self):
    print("mango test")
a = Apple()
a.appletest()
a.mangotest()

输出正常,

我的苹果苹果测试芒果测试

一旦输入a。我可以看到appletest但没有mangotest作为提示。我如何在编辑器中实现它?

“”

python-3.x pycharm
1个回答
0
投票

由于您是如何设置的,所以仅在运行时将附加方法添加到类中。 PyCharm不会不断运行您的代码,以查看每个类都具有哪些方法才能给您带来很好的提示。

我熟悉的任何其他IDE也是如此。

您的IDE对类和实例的方法和属性的了解几乎绝不在实际类(以及任何父类)中的编码范围之内。

即使没有包装器或装饰器,也可以进行测试。在类定义之后(甚至在__init__方法内部)单独拥有此命令:

setattr(Apple, 'test', 'test)

并且即使尝试写入Apple.test,您也永远不会得到提示,即使该属性在此处,我们也会正确返回'test'

© www.soinside.com 2019 - 2024. All rights reserved.