2017-07-15 135 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