Home  >  Q&A  >  body text

Python - Return a new instance of itself through a class method

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!

漂亮男人漂亮男人2685 days ago564

reply all(2)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-18 10:55:17

    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)

    reply
    0
  • 某草草

    某草草2017-05-18 10:55:17

    def newid(self):
            self.id = self.id + 1    # 这里self.id 已经是2了
            return A(self.id)

    Generate y correctly

    What is the correct y

    reply
    0
  • Cancelreply