1

嗨,我有以下超级类

class Room:
    def __init__(self,building,floor,number):
        self.building=building
        self.floor=floor
        self.number=number
    def __str__(self):
        return (str(self.building)+'.'+str(self.floor)+'.'+str(self.number))

和以下子类

class Occupant(Room):
    def __init__(self,familyname,givenname,building,floor,number):
        self.familyname=familyname
        self.givenname=givenname
        Room.__init__(self,building,floor,number)
    def __str__(self):
        return (str(self.familyname)+', '+str(self.givenname)+......)

子类如何打印超类中的元素。当我从类 Occupant 打印对象时,我应该添加到(.....)以获取正确的输出。谢谢

4

1 回答 1

5

AnOccupant似乎是一个人,而 aRoom是一个位置。Occupant如果是这样,那么说 an是 的类型是没有意义的Room。所以Occupant不应该是Room. 相反, anOccupant 有一个 Room

class Room:
    def __init__(self, building, floor, number):
        self.building = building
        self.floor = floor
        self.number = number
    def __str__(self):
        return (str(self.building)+'.'+str(self.floor)+'.'+str(self.number))

class Occupant:
    def __init__(self, familyname, givenname, room):
        self.familyname = familyname
        self.givenname = givenname
        self.room = room

    def __str__(self):
        return '{f}, {g} -- {r}'.format(f = self.familyname, g = self.givenname, r = self.room)

room = Room('Building', 'Floor', 'Num')
occ = Occupant('Family', 'Given', room)
print(occ)
# Family, Given -- Building.Floor.Num
于 2012-06-17T14:20:11.267 回答