如何复制一个类的实例?

时间:2018-08-04 12:50:06

标签: python

到目前为止,我已经用C,C ++和Java完成了编程。 Python是全新的,所以这个问题在我看来有点尴尬。我创建了两个实例box1(矩形类)和box2(矩形类)。作为成员Rectangle内的类Point的实例的成员p似乎在两个实例(box1和box2)之间共享。如何使实例完全独立?

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)

输出:

错误 是

1 个答案:

答案 0 :(得分:1)

这就是为什么在python中使用__init__(self)方法实例化类的原因。

如果您将代码更改为

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