我正在尝试运行此代码并出现错误
这是代码:
# File oop.py
class Person():
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def firstname(self):
return self.name.split()[0]
def lastname(self):
return self.name.split()[-1]
def giveRaise(self,percent):
self.pay = int(self.pay * (1 + percent))
class Manager(Person):
def __init__(self, name, pay):
Person.__init__(self, name, 'mgr', pay)
def giveRaise(self, percent, bonus = .10):
Person.giveRaise(self, percent + bonus)
if __name__ == '__main__':
#self-test code
chris = Manager('Chris Jones', 50000)
chris.giveRaise(.20)
print(chris)
这是我得到的确切错误。我不知道我的代码有什么问题。请帮我解决。
Traceback (most recent call last):
File "main.py", line 29, in <module>
chris.giveRaise(.20)
File "main.py", line 24, in giveRaise
Person.giveRaise(self, percent + bonus)
AttributeError: class Person has no attribute 'giveRaise'
答案 0 :(得分:2)
发生这种情况是由于Person.__init__
缩进。 python假定firstname
,lastname
和giveRaise
的全部都是__init__
函数的局部函数。 (您可以在该函数中定义它们)。因此,请按以下步骤修复缩进:
class Person:
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def firstname(self):
return self.name.split()[0]
def lastname(self):
return self.name.split()[-1]
def giveRaise(self,percent):
self.pay = int(self.pay * (1 + percent))
class Manager(Person):
def __init__(self, name, pay):
Person.__init__(self, name, 'mgr', pay)
def giveRaise(self, percent, bonus = .10):
Person.giveRaise(self, percent + bonus)
if __name__ == '__main__':
chris = Manager('Chris Jones', 50000)
chris.giveRaise(.20)
print(chris.pay)
您的代码将起作用。
请注意,最好使用super
代替Person,如下所示:
class Manager(Person):
def __init__(self, name, pay):
super(Manager, self).__init__(name, 'mgr', pay)
def giveRaise(self, percent, bonus = .10):
super(Manager, self).giveRaise(percent + bonus)