python - Object appended to a list instance appears in a different instance of that list -


I was writing this small piece of code as an exercise in object-oriented programming.

Here I am trying to define a house and every room as a list of devices (lamp, for example) as a list of rooms.

At first I created all the items and added those two rooms to the house and a separate device in each room. Pretty basic

The problem is that it seems that the device is being connected to both rooms. Why is it like this?

Code:

  #! / House / room / room: house / house / room / house: deft __int __ (self, room = list): self Room = room print ('home made') class room: def __init __ (self, name = 'one room', devs = list): self.name = name self.devs = devs print ('room' + self .name + 'created') Category device: def __init __ (self, name = 'a device'): self.name = name Print ('device' + self.name + 'created') DEF main (): # 1 H = House () R1 = Room (name = 'r1') r2 = cell (name = 'r2') = 1 = device name = 'lamp 1') d2 = device (name = 'lamp2') # 2 H. rooms.append (r1) h.rooms.append (r2) Room in the H room: Print room. Name print H.Room [0] Print H.Room [1] H.Room [1] .devs. Append (d1) Thousands # 3 in the room Print: Print room for dev.name in room room. Name: print ('room' + room.name + '' gt; '+ dev.name) print room print god if __name__ ==' __main__ ': main ( )  

and output.

Home made room R1 built room R2 built device lamps 1 built lamp 2 built R1 r2 & lt; __ Main__. 0xb7d8a58c & gt; & Lt; __ Main__. 0xb7d8a5ac & gt; R1 Room R1 & gt; Lamp1 & lt; __ Main__. 0xb7d8a58c & gt; & Lt; __ Main __. Example of device 0xb7d8a5cc & gt; R2 Room R2 & gt; Lamp1 & lt; __ Main__. 0xb7d8a5ac & gt; & Lt; __ Main __. Example of device 0xb7d8a5cc & gt;

Note that the same example of D1 is in both rooms, R1 and R2.

The default parameter values ​​for tasks are only evaluated once it means that all the examples of the house Use the same list example for self.rooms (if the room was not built in construction), for all examples of the room, self.devs Will share the same list.

To resolve this, type the code like this:

  def __init __ (self, room = none): If none of the rooms have: rooms = [] Self.rooms = rooms print ('house created')  

And the only thing for this is the other classes.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

jquery - SimpleModal Confirm fails to submit form -

php - Multiple Select with Explode: only returns the word "Array" -