告诉PyCharm代码生成的类字段

dei*_*aur 8 python docstring pycharm python-2.7

作为一个最小的案例,我有一个Example类似于一系列其他类的抽象容量.

class Example(object):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)            

class Test(Example):
    def __init__(self, foo='bar'):
        super(Test, self).__init__(foo=foo)
Run Code Online (Sandbox Code Playgroud)

在实际情况下,Example做更多的事情.

有没有办法Test通知PyCharm Test将有一个字段Test.foo甚至更好,让它知道foo预计会是一个字符串?

需要明确的是,请考虑将字段设置委托ExampleTest不可能.

我得到的最接近的@ivar是Epydoc,但我无法让它发挥作用

小智 7

正如其他人所说,你不能.但是,您可以告诉PyCharm接受缺少的属性@DynamicAttrs:

class Example(object):
   """
   @DynamicAttrs
   """
   def __init__(self, **kwargs):
      for key, value in kwargs.items():
         setattr(self, key, value)
Run Code Online (Sandbox Code Playgroud)

更新: 如果Python3.5是一个选项,请参阅有关为动态属性使用类型提示的此问题.


Ram*_*ast 3

我遇到了你所面临的完全相同的问题。我不需要代码建议,我只是希望 PyCharm 停止警告我有关未定义的属性 ( foo is not attribute of class Test)

我无法修复代码提示问题,但我通过实现Example这样的类克服了警告

class Example(object):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)            

    def __getattr__(self, name):
        """
        Does absolutely nothing, only for pycharm to stop complaining about massing attributes
        This function is *only* called when python fail to find certain attribute, so it always raises exception
        """
        raise AttributeError("Attribute %s is not part of %s class" % (name, self.__class__.__name__))
Run Code Online (Sandbox Code Playgroud)