2012-08-22 117 views
2

我遇到了我的代碼問題。我試圖創建一個繼承父類的屬性和方法的子類,但它不起作用。這是我到目前爲止:不繼承父類的子類

class Employee(object): 
    def __init__(self, emp, name, seat): 
    self.emp = emp 
    self.name = name 
    self.seat = seat 

下面的代碼塊 - 子類有問題。

我必須再次創建__init__嗎?我該如何爲子類創建一個新的屬性。從閱讀問題,這聽起來像__init__在子類中將重寫父類 - 如果我稱它來定義另一個屬性是真的嗎?

class Manager(Employee): 
    def __init__(self, reports): 
    self.reports = reports 
    reports = [] 
    reports.append(self.name) #getting an error that name isn't an attribute. Why? 

    def totalreports(self): 
    return reports 

我想要Employee類中的名稱在報告列表中。

舉例來說,如果我有:

emp_1 = Employee('345', 'Big Bird', '22 A') 
emp_2 = Employee('234', 'Bert Ernie', '21 B') 

mgr_3 = Manager('212', 'Count Dracula', '10 C') 

print mgr_3.totalreports() 

我想reports = ['Big Bird', 'Bert Ernie'],但它不工作

+0

[錯誤的可能重複:「X實例有沒有屬性y「當試圖從類繼承](http://stackoverflow.com/questions/6143693/error-x-instance-has-no-attribute-y-when-trying-to-inherit-from-class ) –

+0

'我要報告= ['大','鳥']但它不起作用 - 你的意思是'報告=''大鳥','伯特厄尼']?如果是這樣,那不是繼承是如何工作的。 Manager類不知道您以前創建的任何Employee實例*。還是你得到一個不同的錯誤? –

回答

7

你從沒叫父類的__init__功能,這也正是這些屬性的定義:

class Manager(Employee): 
    def __init__(self, reports): 
    super(Manager, self).__init__() 
    self.reports = reports 

爲此,您需要修改Employee類的__init__函數並給出參數的默認值:

class Employee(object): 
    def __init__(self, emp=None, name=None, seat=None): 
    self.emp = emp 
    self.name = name 
    self.seat = seat 

而且,這個代碼將不能在所有的工作:

def totalreports(self): 
    return reports 

reports的範圍只在__init__功能,所以它是不確定的。您必須使用self.reports而不是reports

至於你最後的問題,你的結構不會真的讓你做得很好。我將創建第三個類來處理員工和經理:

class Business(object): 
    def __init__(self, name): 
    self.name = name 
    self.employees = [] 
    self.managers = [] 

    def employee_names(self); 
    return [employee.name for employee in self.employees] 

你必須通過它們附加到相應的列表對象的員工加入到企業。

-1

你需要在適當的地方運行超類的初始化(),加上捕獲(未知的子類)的參數,並通過他們起來:

class Manager(Employee): 
    def __init__(self, reports, *args, **kwargs): 
    self.reports = reports 
    reports = [] 
    super(Manager, self).__init__(*args, **kwargs) 
    reports.append(self.name) #getting an error that name isn't an attribute. Why? 
+0

這個答案爲什麼downvoted? – slim