3

So i have this class in python

class room (object):

    def __init__(self,number):
        self.room_number=number

    def get_room_num(self):
        return self.room_number

And i have another class called House, basically when i create the house object, i also need to create room objects for the house, and the number of rooms will be chosen by the user.

I have difficulty with creating dynamic objects (since it is specified by the user, we would have 1 room or 10 room), i can't give each room object a name since i won't know how many there are before hand.

So i tried like this

class House (object):

    def __init__(self,num_of_rooms):
        self.room_holder=[]
        for i in range(num_of_rooms):
            self.room_holder.append(room(i))

    def __iter__(self):
        return iter(self.room_holder)

is there a better way to do it?, if so please help

the iter function is there so i can iterate over it, example

mansion=House(10)

for i in mansion:
    print i.get_room_num()
1
  • 2
    By the way, if you're just looking for a general review of your code, and don't have a specific question, you might consider codereview.stackexchange.com Commented Jun 7, 2012 at 2:42

2 Answers 2

6
class Room(object):      # note: class name is Capitalized
    def __init__(self, number):
        self.number = number

    # get_ methods are non-Pythonic.
    # If you need to do some processing to retrieve room number,
    # make it a @property; otherwise, just use the field name

class House(object):
    def __init__(self, num_rooms):
        # I assume you don't want a room 0?
        self.rooms = [Room(i) for i in range(1, num_rooms+1)]
    def __iter__(self):
        return iter(self.rooms)

mansion = House(10)
for room in mansion:
    print room.number
Sign up to request clarification or add additional context in comments.

Comments

3

There's nothing wrong with what you have there. Is there a better way? Well, you could use a list comprehension, I guess:

class House(object):
  def __init__(self, num_rooms):
    self.rooms=[room(i) for i in xrange(num_rooms)]
  def __iter__(self):
    return iter(self.rooms)

These are essentially stylistic changes though. As I said, I see nothing wrong with what you have.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.