0

So far I've done programming in C, C++, and Java. Python is totally new so this problem seems kind of awkward to me. I created two instances box1 (class Rectangle) and box2 (also class Rectangle). The member p which is an instance of the class Point inside the class Rectangle seems to be shared between both instances (box1 and box2). How to make the instances completely independent?

import copy

class Point:
    x=0
    y=0

class Rectangle:
    width=0
    height=0
    p=Point()

box1=Rectangle()

box1.width=5
box1.height=6
box1.p.x=2
box1.p.y=3

box2=Rectangle()

print(box1 is box2)

print(box1.p is box2.p)

Output:

False True

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

This is why in python you instantiate classes with the __init__(self) method.

If you change your code to

class Point:
    def __init__(self):
        self.x = 0
        self.y = 0
class Rectangle:
     def __init__(self):
        self.width = 0
        self.height = 0
        self.p = Point()
box1=Rectangle()

box1.width=5
box1.height=6
box1.p.x=2
box1.p.y=3

box2=Rectangle()

print(box1 is box2) # output is false

print(box1.p is box2.p) # output is false
Jonathan R
  • 3,652
  • 3
  • 22
  • 40