2016-10-17 69 views
1

我正在學習python中的OOP。瞭解Python中的繼承問題

我掙扎着爲什麼這不按照我的意圖工作?

class Patent(object): 
    """An object to hold patent information in Specific format""" 
    def __init__(self, CC, PN, KC=""): 
     self.cc = CC 
     self.pn = PN 
     self.kc = KC 

class USPatent(Patent): 
    """"Class for holding information of uspto patents in Specific format""" 
    def __init__(self, CC, PN, KC=""): 
     Patent.__init__(self, CC, PN, KC="") 


pt1 = Patent("US", "20160243185", "A1") 

pt2 = USPatent("US", "20160243185", "A1") 

pt1.kc 
Out[168]: 'A1' 

pt2.kc 
Out[169]: '' 

我在做什麼明顯的錯誤,使我無法在美國專利實例中獲得kc?

回答

4

你傳遞一個空字符串:

Patent.__init__(self, CC, PN, KC="") 

這總是調用Patent.__init__()方法設置KC""

通行證在KC任何價值,你收到的,而不是:

class USPatent(Patent): 
    """"Class for holding information of uspto patents in Specific format""" 
    def __init__(self, CC, PN, KC=""): 
     Patent.__init__(self, CC, PN, KC=KC) 

USPatent.__init__()KC只是另一個變量,就像selfCCPN。它已設置爲"",或者當您調用帶參數的USPatent(...)時傳入的值。您只需調用Patent.__init__()方法傳遞您擁有的所有值。

您可以從掉話關鍵字參數語法太:

Patent.__init__(self, CC, PN, KC) 
+0

我仍然不明白使用KC = KC? – Rahul

+0

@Rahul:如果你爲你的函數添加了print(CC,PN,KC),它會有幫助嗎?你會看到值發生了什麼。 –

+1

@Rahul注意''當[使用默認關鍵字參數定義一個函數]時,'KC =「」'意味着不同的事情(https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions )而不是[使用關鍵字參數調用函數](https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments)。 – tutuDajuju

1
class USPatent(Patent): 
    """"Class for holding information of uspto patents in Specific format""" 
    def __init__(self, CC, PN, KC=""): 
     Patent.__init__(self, CC, PN, KC="") 

在這裏您可以通過編碼KC=""通過KC"",而不是KC=KC

要通過輸入KC

class USPatent(Patent): 
    """"Class for holding information of uspto patents in Specific format""" 
    def __init__(self, CC, PN, KC=""): 
     Patent.__init__(self, CC, PN, KC) 
+0

謝謝。我知道了 – Rahul

1

Patent.__init__(self, CC, PN, KC="") 

應該

Patent.__init__(self, CC, PN, KC) 

前者設置的名稱參數「 KC「改爲值""(空字符串)使用關鍵字樣式參數語法。你想要的是傳遞變量KC的值。

+0

謝謝。我知道了 – Rahul