Rave
Rave

Reputation: 843

Creating objects inside a Class in python

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()

Upvotes: 3

Views: 23490

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56624

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

Upvotes: 6

kojiro
kojiro

Reputation: 77059

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.

Upvotes: 3

Related Questions