Back

Explore Courses Blog Tutorials Interview Questions
0 votes
6 views
in Python by (45.3k points)

These variable assignments work as I expect:

>>> a = 3

>>> b = a

>>> print(a, b)

(3, 3)

>>> b=4

>>> print(a, b)

(3, 4)

However, these assignments behave differently:

>>> class number():

...     def __init__(self, name, number):

...         self.name = name

...         self.number = number

... 

>>> c = number("one", 1)

>>> d = c

>>> print(c.number, d.number)

(1, 1)

>>> d.number = 2

>>> print(c.number, d.number)

(2, 2)

Why is c is same as d, unlike in (a, b) example? How can I do something like in (a, b) in (c, d) classes example? That is, copy the object and then change one part of it (that won't affect the object that I borrowed properties from)?

1 Answer

0 votes
by (16.8k points)

I didn't see that anyone provided details on how to make these two cases work the same by copying the object instead of just assigning a new reference to the same object.

import copy

c = number("one", 1)

d = c

e = copy.copy(c)

print(c.number, d.number, e.number)

d.number = 2

e.number = 5

print(c.number, d.number, e.number)

This will give you:

1 1 1

2 2 5

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)

Browse Categories

...