【问题标题】:Unresolved Reference Warning in Docstring - Python 3.6 - Pycharm 17.1.4文档字符串中未解决的参考警告 - Python 3.6 - Pycharm 17.1.4
【发布时间】:2017-07-16 07:08:09
【问题描述】:

我从 PyCharm 收到有关未解析引用的警告。 这是结构类似的代码,也应该收到警告。

class Parent:
    """
    === Attributes ===
    @type public_attribute_1: str
    """

    def __init__(self):
        public_attribute_1 = ''
    pass

class Child(Parent):
    """
    === Attributes ===
    @type public_attribute_1: str
        > Unresolved reference 'public_attribute_1'
    @type public_attribute_2: str
    """

    def __init__(self):
        Parent.__init__(self)
        public_attribute_2 = ''

    pass

我知道public_attribute_1 不是在Child.__init__() 中显式启动的,而是Child.__init__() 调用Parent.__init__(self) 启动public_attribute_1。因此,引发的错误与功能性和可读性有关。

如何在不插入冗余的情况下使此类代码更具可读性,从而破坏整个继承点? 通过 docstrings 和 cmets 彻底记录并忽略 PyCharm 的警告就足够了吗?还是有pythonic的方法?

【问题讨论】:

  • 浮动的passes 是怎么回事?你也应该使用super().__init__()
  • 我使用了pass,因为这些类中的其余代码并不重要。我想他们不是真的有必要,但是是的。

标签: python-3.x inheritance documentation pycharm


【解决方案1】:

这里有很多问题。

  1. Python 3 中使用super()

  2. 您称它们为“属性”,但这不是属性在 Python 中的工作方式。修饰细节,使用self

您的问题似乎是关于您希望Childdocstring 重新定义Parent 的所有属性。从可维护性的角度来看,这是非常危险的,但如果有任何变化的话。当我看到一个类继承了Parent 时,如果我不熟悉Parent,我会去看Parent 的定义(PyCharm 使用Ctrl + B 很容易)。

我会让其他人说这是否真的是pythonic,但这是我习惯的工作方式。无论如何,要修复您的继承,您的代码应该看起来更像这样:

class Parent:
    """
    === Attributes ===
    @type public_attribute_1: str
    """

    def __init__(self):
        self.public_attribute_1 = ''


class Child(Parent):
    """
    === Attributes ===
    @type public_attribute_2: str
    """

    def __init__(self):
        super().__init__()
        self.public_attribute_2 = ''
        print(self.public_attribute_1)

【讨论】:

  • 感谢您的意见!请问Parent.__init__(self)super.__init__()的区别?我通过一门课程学习了python,并通过Parent.__init__(self)学习了继承,该课程是针对Python 3的。
猜你喜欢
  • 1970-01-01
  • 2016-11-04
  • 2014-05-05
  • 1970-01-01
  • 2014-02-09
  • 2015-11-12
  • 1970-01-01
  • 2020-04-24
相关资源
最近更新 更多