2017-07-15 136 views
0

我收到来自PyCharm的有关未解决的引用的警告。 这是代码结构相似,并且也应该收到警告。Docstring中未解决的引用警告 - Python 3.6 - Pycharm 17.1.4

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_1Child.__init__()明确启动,但Child.__init__()调用Parent.__init__(self)从而启动public_attribute_1。因此,所提出的错误涉及可读性和文档而不是功能。

我怎样才能使这样的代码更具可读性,而不插入冗余,从而击败整个继承点? 是否足以通过文档和注释进行彻底的文档化,并且忽略来自PyCharm的警告?或者是否有一种pythonic的方式呢?

+0

什么是浮动'pass'es?你也应该使用'super().__ init __()'。 – jonrsharpe

+0

我使用了'pass',因为这些类中的其他代码并不重要。我猜他们不是很有必要,但是你。 – Amaranth

回答

0

这里有很多问题。

  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) 
+0

感谢您的意见!我能问一下'Parent .__ init __(self)'和'super .__ init __()'之间的区别吗?我通过课程学习了python,并且通过使用'Parent .__ init __(self)'来学习继承,并且课程是针对Python 3的。 – Amaranth