无法访问子类中的父类变量

时间:2017-09-28 13:02:34

标签: python python-3.x

据我所知,子类可以访问父类的变量。但我无法这样做。

父类

class Room:

    rooms = {}

    def __init__(self):
        self.roomno = 0
        self.rcap = 0

    def addRoom(self):
        self.rcap = input("Please enter room capacity:\n")
        self.rooms[self.roomno] = self.rcap

儿童班

class Booking(Room):

    def __init__(self):
        self.nog = 0

    def addBooking(self):
        global status
        rno = input("Please enter room number:\n")
        self.roomcheck(rno)
        while status is False:
            self.nog = input("Please enter number of guests:\n")
            while int(self.nog) > int(self.rcap):
                print("Guest count exceeds room capacity of: %d" % int(self.rcap))

主菜单

z = Booking()

def mainMenu():
    choice = input()
    if choice == '2':
        z.addRoom()

mainMenu()

我收到如下错误:

File "D:/hotel/hotel6.py", line 159, in addBooking
    while int(self.nog) > int(self.rcap):
AttributeError: 'Booking' object has no attribute 'rcap'

2 个答案:

答案 0 :(得分:0)

我无法重现您的问题。我不得不修改你的示例代码,因为它缺少一些变量,所以它看起来像:

class Room:                                                                     

    def __init__(self):                                                         
        self.roomno = 0                                                         
        self.rcap = 0                                                           
        self.rooms = {}                                                         
        self.nog = 10                                                            

    def addRoom(self):                                                          
        self.rcap = input("Please enter room capacity:\n")                      
        self.rooms[self.roomno] = self.rcap                                     

class Booking(Room):                                                            
    def addBooking(self):                                                       
        while int(self.nog) > int(self.rcap):                                   
            print("Guest count exceeds room capacity of: %d" % int(self.rcap))  

x = Booking()
x.addRoom()
x.addBooking()

如果我跑这个,我得到:

Please enter room capacity:
5
Guest count exceeds room capacity of: 5

当然,最后一行会永远重复,因为那里有无限循环,但变量访问没有问题。

答案 1 :(得分:0)

只有当某些东西在概念上与其他东西实际上是同一种对象时,才应该使用继承。预订不是房间,所以继承没有意义。我也不知道与Room.rooms的交易是什么,无论这是某种时髦的静态变量还是误用的实例变量 - 无论如何,对于像这样的代码,Room应该有跟踪房间 - 这应该由另一个班级(酒店,也许)完成。更好的房间和预订模型可能看起来像这样:

class Hotel:
    def __init__(self):
        self.rooms = {}

    def add_room(self, room):
        self.rooms[room.number] = room

    @classmethod
    def from_rooms(cls, rooms):
        self = Hotel()
        for r in rooms:
            self.add_room(r)
        return self

    def __str__(self):
        return "Hotel with rooms:\n{}".format("\n".join(map(str, self.rooms.values())))

class Room:
    def __init__(self, number, capacity):
        self.number = number
        self.capacity = capacity

    def __str__(self):
        return "Room {} ({} people)".format(self.number, self.capacity)

class RoomFullError(Exception):
    pass

class Booking:
    def __init__(self, room, guests):
        if guests > room.capacity:
            raise RoomFullError("This room can only have {} guests, not {}".format(room.capacity, guests))
        else:
            self.room = room
            self.guests = guests

    def __str__(self):
        return "Booking for {} guests at room ({})".format(self.guests, self.room)

h = Hotel.from_rooms([Room("001", 3), Room("123", 10)])
h.add_room(Room("666", 1))
print(h)
print(h.rooms["001"])
b = Booking(h.rooms["001"], 2)
print(b)
Booking(h.rooms["123"], 500)

这将输出:

Hotel with rooms:
Room 001 (3 people)
Room 123 (10 people)
Room 666 (1 people)
Room 001 (3 people)
Booking for 2 guests at room (Room 001 (3 people))
Traceback (most recent call last):
  File "code.py", line 46, in <module>
    Booking(h.rooms["123"], 500)
  File "code.py", line 32, in __init__
    raise RoomFullError("This room can only have {} guests, not {}".format(room.capacity, guests))
__main__.RoomFullError: This room can only have 10 guests, not 500

注意,预订仍然可以访问房间而不会继承房间,只是因为它通过了__init__的房间。

这只是您可能会做的大致概述,因为我不知道您项目的全部细节。您可能应该有Hotel的方法来处理和存储预订或其他内容。要带走的重要一点是,没有什么需要从这里继承任何东西,你应该定义具有其他类的实例作为属性的单独的类。