Variable identifier with Python __init__ function - can anyone explain?

I have a query about the functions of the init class in Python. I was busy trying to create an environment such as a text adventure game, with each room having a "items" property, which is stored as a list. I tried the following:

Class Room:

def __init__(self,items=[]):
    self.items=items

But what I find in this is that every room that does not have an element defined in initiation receives not only an empty list, but the same empty list. Now, if I create a bunch of rooms and add an item to one of them, the item will appear in each room.

It’s easy enough to fix it (manually assign an empty list to each room), but I don’t understand why this is happening. I would suggest that creating room a will create a.items as an empty list, and room b will create b.items. But can anyone explain why they would be identical? And is there a way to create the above function with a default value that creates a different list each time?

Greetings

Billy.

+3
source share
1 answer

python. items = [], [], , . , , , [] . (, Java, - . ).

: http://effbot.org/zone/default-values.htm

:

def __init__(self, items=None):
    if items is None:
        items = []
    self.items = items

, , None, . , ( , ).

+3

All Articles