0

这是我的代码

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

4

2 回答 2

5

您尚未发布的是您创建的两条消息__setattr__

Invalid officer rank
Invalid officer rank

这些来自以下几行:

self.name = name
self.gender = gender

由于这些失败,您以后无法检索名称:

 print 'Hi there, I am '+ self.name

使固定:

def __setattr__(self, key, value):
    if key == "rank" and value not in [.....]
于 2012-08-25T22:30:16.737 回答
0

您在任何时间以任何方式设置__setattr__任何属性时都会调用您,包括在通过超类初始化期间。Officer__init__

__setattr__被调用时,self将是Officer实例,rank将是要设置的属性的名称,并且value将是该属性所需的值。

您所做的是使Officer该类可以对.lieutenant列表中的值具有等,但不能具有.rank(或.name.gender)-并且您实际上根本没有限制该属性的值。

这比你想要的更深奥的魔法;您显然想限制专门设置属性时使用。为此,请使用属性。.rank

于 2012-08-26T03:34:21.653 回答