这是我的代码
class Human(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
print 'Hi there, I am '+ self.name
def ThankHeavens(self):
return 'Thanks Gods!'
class Soldier(Human):
def __init__(self, name, gender, rank):
super(Soldier, self).__init__(name, gender)
self.rank = rank
print self.rank + ' reporting!'
class Officer(Soldier):
def __init__(self, name, gender, rank, num_subordinates):
super(Officer, self).__init__(name, gender, rank)
self.num_subordinates = num_subordinates
def __setattr__(self, rank, value):
if rank not in ['lieutenant', 'captain', 'major', 'colonel', 'commander', 'admiral']:
print 'Invalid officer rank'
else:
super(Officer, self).__setattr__(rank, value)
每当我尝试创建军官时,它就会中断:
helo = Officer(name='Agathon',
gender='m',
rank='lieutenant',
num_subordinates=0)
Traceback (most recent call last):
File "hw7.py", line 39, in <module>
num_subordinates=0)
File "hw7.py", line 20, in __init__
super(Officer, self).__init__(name, gender, rank)
File "hw7.py", line 14, in __init__
super(Soldier, self).__init__(name, gender)
File "hw7.py", line 7, in __init__
print 'Hi there, I am '+ self.name
AttributeError: 'Officer' object has no attribute 'name'
为什么它不能识别我在定义时输入的名称helo
?