Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 子类不继承父类_Python_Inheritance_Attributes_Parent Child - Fatal编程技术网

Python 子类不继承父类

Python 子类不继承父类,python,inheritance,attributes,parent-child,Python,Inheritance,Attributes,Parent Child,我的代码有问题。我试图创建一个继承父类的属性和方法的子类,但它不起作用。以下是我目前掌握的情况: class Employee(object): def __init__(self, emp, name, seat): self.emp = emp self.name = name self.seat = seat 下面的代码块(子类)有问题 我是否必须再次创建\uuuu init\uuuu?以及如何为子类创建新属性。从阅读问题中,听起来像是子类中的\uuuu i

我的代码有问题。我试图创建一个继承父类的属性和方法的子类,但它不起作用。以下是我目前掌握的情况:

class Employee(object): 
  def __init__(self, emp, name, seat):
    self.emp = emp
    self.name = name
    self.seat = seat
下面的代码块(子类)有问题

我是否必须再次创建
\uuuu init\uuuu
?以及如何为子类创建新属性。从阅读问题中,听起来像是子类中的
\uuuu init\uuuu
将覆盖父类-如果我调用它来定义另一个属性,这是真的吗

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

您从未调用父类的
\uuuuuu init\uuuu
函数,这些属性就是在该函数中定义的:

class Manager(Employee): 
  def __init__(self, reports):
    super(Manager, self).__init__()
    self.reports = reports
为此,您必须修改
Employee
类的
\uuuu init\uuuu
函数,并为参数提供默认值:

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
报告
的作用域仅在
\uuuuu init\uuuu
函数中,因此它将是未定义的。您必须使用
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]

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

您需要在适当的位置运行超类的init(),并捕获(子类未知)参数并将其传递:

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? 

可能重复的
I-want reports=['big','bird'],但它不起作用
——你是说
reports=['big bird','Bert Ernie']
?如果是这样,继承就不是这样工作的。Manager类不知道您以前创建的任何Employee实例。或者,您是否遇到了不同的错误?