Help (I can't think of a better title)
duncan smith
buzzard at urubu.freeserve.co.uk
Sun May 23 11:57:54 EDT 2010
Alex Hall wrote:
> On 5/22/10, MRAB <python at mrabarnett.plus.com> wrote:
>> Lanny wrote:
>>> The answer may be right infront of me but I really can't figure this
>>> out.
>>> I'm trying to build a interactive fiction kind of game, silly I know
>>> but I
>>> am a fan of the genre. I'm trying to build up an index of all the
>>> rooms in
>>> the game from an outside file called roomlist.txt. The only problem is
>>> that
>>> every room ends up having four exits. Here's the code.
>>>
>>>
>>> class room() :
>>> room_id = 'room_id'
>>> name = 'room'
>>> description = 'description'
>>> item_list =
>>> exits = {}
>> > visits = 0
>>
>> These attributes are being defined as belonging to the class, so they
>> will be shared by all the instances of the class. This isn't a problem
>> for immutable items such as strings, but is for mutable items such as
>> dicts. In short, all the rooms share the same 'exits' dict.
>>
>> You should really define the instance attributes (variables) in the
>> '__init__' method.
>
> I just ran into something similar to this in my Battleship game. I had
> a Craft class, which defined attributes for any craft (a recon plane,
> a submarine, a battleship, and so on). One such attribute was a
> weapons list, much like your exits dictionary; I would assign a couple
> weapons to a battleship, but suddenly all my ships and airplanes had
> those same weapons. What the great people on this list said to do was
> something like this:
>
> class Room():
> def __init__(self, exits):
> if exits==None:
> self.exits={}
> else:
> self.exits=exits
>
> In this way, you can create a new Room object with exits,
> r=Room(exits_dict)
> or you can create a Room with no exits, and add them later:
> r2=Room()
> r2.exits["exit1"]="doorway"
>
> but the code in the __init__ method, which will get called as soon as
> you create a new Room object, ensures that passing an exits dictionary
> will set that instance's exits to what was passed in, while passing
> nothing will create a room with an empty dictionary (the if
> statement). I hope this made some sense!
[snip]
It does when when you want 'exits' to take a default value which is a
mutable type (and you don't want it shared by all instances).
class Room:
def __init__(self, exits=None):
if exits is None:
self.exits = {}
else:
self.exits = exits
Otherwise, you're fine without the if ... else.
Duncan
More information about the Python-list
mailing list