扩展类继承自基类的一个方法行为,然后如果想要把基类的这个行为重新执行一遍,在自己的这个行为前面加上基类的引用,super后面为啥要加一个括号呢?直接写super.working()就报错了。。
而且,这里写基类的名字,Employee().working()也会报错。。只能用super().working(),为啥啊。。
代码如下:
class Employee:
def __init__(self,name,department,title,salary):
self.name = name
self.department = department
self.title = title
self.salary = salary
def __repr__(self):
return f'员工:{self.name}'
def working(self):
print(f'员工{self.name}在工作...')
class Developer(Employee):
def __init__(self,name,department,title,salary,skills):
Employee.__init__(self,name,department,title,salary)
self.skills = skills
def working(self):
super().working()
print('开发人员在工作')
class Accountant(Employee):
def __init__(self,name,department,title,salary,certification):
Employee.__init__(self,name,department,title,salary)
self.certification = certification
if name == '__main__':
d = Developer('tom','技术部','高级工程师','13000',['python','flask'])
print(d.name)
d.working()
3 回答

慕的地8271018
TA贡献1796条经验 获得超4个赞
- super后面为啥要加一个括号?
super是一个函数,函数的调用就需要加括号,直接super.working()相当于调用super这个对象的working方法,而它没有这个方法,所以会报错。 - Employee().working()报错,Employee().working()是实例化一个类之后,调用这个类的working方法,实例化Employe需要传入name,department,title,salary这几个参数,改成Employee(name=xxx, department=xxx, title=xxx, salary=xxx).working()就可以了。

慕桂英4014372
TA贡献1871条经验 获得超13个赞
1.super用于实例化一个对象用于调用实例方法
2.你那里调用基类无效是因为working是一个实例方法,你如果用初始化参数传进类生成一个实例,你那样用基类调用应该也是ok的
添加回答
举报
0/150
提交
取消