Python - Return a new instance of itself through a class method
漂亮男人
漂亮男人 2017-05-18 10:53:17
0
2
559

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!

漂亮男人
漂亮男人

reply all(2)
给我你的怀抱

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)

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

Generate y correctly

What is the correct y

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!