Python 装饰器/类方法 &皮查姆 [英] Python Decorator/Class method & Pycharm
问题描述
为什么在NextTip(Pycharm)中没有显示装饰方法
from functools import wrapsdef add_method(cls):定义装饰器(函数):@wraps(func)def 包装器(self, *args, **kwargs):返回 func(self, *args, **kwargs)setattr(cls, func.__name__, 包装器)返回函数返回装饰器类苹果():def __init__(self):打印(我的苹果")def appletest(self):打印(苹果测试")@add_method(苹果)def mangotest(自我):打印(芒果测试")a = 苹果()a.appletest()a.mangotest()
输出很好,
我的苹果苹果测试芒果测试
一旦我输入a.我可以看到 appletest 但不是 mangotest 作为我的提示.我怎样才能在我的编辑器中实现它?
附加方法只会在运行时添加到类中,因为您如何设置它.PyCharm 不会不断地运行您的代码来查看每个类都有哪些方法只是为了给您很好的提示.
这也适用于我熟悉的任何其他 IDE.
您的 IDE 对类和实例的方法和属性的了解程度几乎从未超出实际类(和任何父类)中编码的内容.
即使没有包装器或装饰器,您也可以对其进行测试.在类定义之后(甚至在 __init__
方法中)单独使用此命令:
setattr(Apple, 'test', 'test')
并且在尝试编写 Apple.test
时您永远不会得到提示,即使该属性存在并且会正确返回 'test'
值>
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 ?
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
这篇关于Python 装饰器/类方法 &皮查姆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!