Define a class A and have a method with its own ID 1. The code is as follows:
class A(object):
def __init__(self, id):
self.id = id
def newid(self):
self.id = self.id + 1
return A(self.id)
Define instance x as class A, id is 1, print x.id:
[In]:
x = A(1)
print(x.id)
[Out]:
1
Now I want to create an instance y that is also a class A, and create it through the newid method of class A:
[In]:
y = x.newid()
print(y.id)
[Out]:
2
You can get the accurate ID of y as 2, but you find that the ID of x has also been modified:
[In]:
print(x.id)
[Out]:
2
How can I correctly generate y without modifying the original instance x? Thank you!
def newid(self):
self.id = self.id + 1
return A(self.id)
This is bound to change
Why do you want it to remain unchanged +1
It should be return A(self.id+1)
What is the correct y