Python Decorator/Class method & Pycharm

我与影子孤独终老i 提交于 2020-01-24 23:31:07

问题


Why doesn't the decorated method doesn't show up in 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()

Output is fine,

my apple apple test mango test

Once I type a. I can see appletest but not mangotest as my tip. How can i achieve it in my editor ?


回答1:


The additional method only gets added to the class at runtime because of how you set that up. PyCharm doesn't run your code constantly to see what methods every class have just to give you good hints.

This is also true of any other IDE I'm familiar with.

The extent to which your IDE know about methods and properties of classes and instances is almost never outside of what is coded in the actual class (and any parent class).

You can test it even without a wrapper or decorator. Have this command by itself after the class definition (or even inside the __init__ method):

setattr(Apple, 'test', 'test')

And you'll never get a hint when trying to write Apple.test, even though that attribute is there and will return the 'test' value correctly



来源:https://stackoverflow.com/questions/58895588/python-decorator-class-method-pycharm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!