1

I try to instanciate two objects of a house with a bedroom and a living room. If i change the pieces of furniture in one house the other one should not change.

class room:
    def __init__(self,name,piecesoffurniture):
        self.name=name
        self.piecesoffurniture=piecesoffurniture
class house:
    def __init__(self,rooms):
        self.rooms=rooms

bedroom=room("bedroom",2)
livingroom=room("livingroom",3)
rooms=[]
rooms.append(bedroom)
rooms.append(livingroom)
myhouse=house(rooms)
yourhouse=house(rooms)
myhouse.rooms[0].piecesoffurniture=4
print(bedroom.piecesoffurniture)
print(yourhouse.rooms[0].piecesoffurniture)

output:

4

4

This is a sample code for my program where the constructor of room is very slow and the constructor of house is very fast.

coder123
  • 27
  • 4
  • 1
    You are using the same list in both cases. Copy the list before instancing the class. – Dschoni Aug 18 '20 at 12:29
  • aside, python class names should be Capitalised – Chris_Rands Aug 18 '20 at 12:29
  • Probably a good general read on (im)mutable objects: https://www.afternerd.com/blog/difference-between-list-tuple/ Especially point 2. Debugging – Dschoni Aug 18 '20 at 12:33
  • there is good rule to use `CamelCaseNames` for classes - `class Room`, `class House` - it helps to recognize class in code. And many IDEs use special colors for these names to make it more readable - even Stackoverflow uses other color for `CamelCaseNames`. You could also use spaces around `=` to make it more readable - see more [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) – furas Aug 18 '20 at 13:06
  • So i copied my list but the output stayed the same: bedroom=room("bedroom",2) livingroom=room("livingroom",3) rooms=[] rooms.append(bedroom) rooms.append(livingroom) room1=rooms room2=rooms myhouse=house(room1) yourhouse=house(room2) myhouse.rooms[0].piecesoffurniture=4 print(bedroom.piecesoffurniture) print(yourhouse.rooms[0].piecesoffurniture) output: 4 4 – coder123 Aug 19 '20 at 07:12
  • If i change my list to a tuple the output also stays the same: bedroom=room("bedroom",2) livingroom=room("livingroom",3) rooms=(bedroom,livingroom) room1=rooms room2=rooms myhouse=house(room1) yourhouse=house(room2) myhouse.rooms[0].piecesoffurniture=4 print(bedroom.piecesoffurniture) print(yourhouse.rooms[0].piecesoffurniture) output: 4 4 – coder123 Aug 19 '20 at 07:23
  • https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent This link solved my problem I had to use copy.deepcopy(list) – coder123 Aug 19 '20 at 07:30

0 Answers0