python - 子类不继承父类

标签 python inheritance attributes parent-child

我的代码有问题。我正在尝试创建一个继承父类的属性和方法的子类,但它不起作用。这是我到目前为止所拥有的:

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'] 但它不起作用

最佳答案

您从未调用父类的 __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]

您必须通过将员工附加到适当的列表对象来将员工添加到业务中。

关于python - 子类不继承父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12066541/

相关文章:

ios - 在swift中使用继承对象的方法

attributes - 单点触控 : Understand Foundation Attributes

python - 来自 Scikit-Learn 的 K 均值的失真函数

python - 使用 Python 的人类可读二进制数据

python - 每个月的第 n 天运行 APScheduler 作业

python - 正确使用 super() 到 .pop() 从每个子实例的父类列表中删除名称

inheritance - 在结构中嵌入两个同名的结构

html - 非标准属性有什么用?

python - 您如何以编程方式设置属性?

python - 为什么 print ("text {}".format(yield i)) 是无效的语法,而 print ("text {}".format((yield i))) 是有效的?