【问题标题】:Tell PyCharm code generated fields of class告诉 PyCharm 代码生成的类的字段
【发布时间】:2015-04-29 12:23:05
【问题描述】:

作为一个最小的例子,我有一个类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)

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

有没有办法在 Test 上通知 PyCharm Test 将有一个字段 Test.foo 甚至更好,让它知道 foo 应该是一个字符串?

为明确起见,考虑将字段设置从Example 委托给Test 是不可能的。

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

【问题讨论】:

  • AFAIK,你不能。如果动态定义对象的成员,则必须忘记提示。您可以在Test 上定义将被实例属性“遮蔽”的类属性,但这不值这个价。忍受它。
  • sigh,好吧,但谢谢你的回答。
  • 是的,可惜,但 Pycharm 必须非常聪明才能理解代码并为您提供提示。在许多情况下,我避免使用“动态”代码而使用“手动键入”代码,只是为了获得更多的安全性并同时享受注释。最后是动态类型语言的普遍问题......IDE不能做太多。

标签: python python-2.7 pycharm docstring


【解决方案1】:

正如其他人所提到的,你不能。但是,您可以使用 @DynamicAttrs 告诉 PyCharm 接受缺失的属性:

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

更新: 如果 Python3.5 是一个选项,请参阅 this question 了解使用动态属性的类型提示。

【讨论】:

    【解决方案2】:

    我遇到了与您完全相同的问题。 我不想要代码建议,我只是想让 PyC​​harm 停止警告我未定义的属性 (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__))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2017-11-30
      • 2010-12-29
      • 2019-10-22
      • 2015-09-20
      相关资源
      最近更新 更多