some value of the variables changed with no reason

Asked by rain

Look at the code directly:
x = Region(find(picture1))
r1 = x
r2 = x

y1 = Region(find(picture2))
y2 = Region(find(picture3))
print y1.y,y2.y

r1.y = y1.y
print r1.y
r2.y = y2.y
print r1.y

result:
481 499
481
499

After assignment to r2.y, why the value of r1.y changed to r2.y? And if there's r3,r4, all value will change to r4.y.

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
rain
Solved:
Last query:
Last reply:
Revision history for this message
RaiMan (raimund-hocke) said :
#1

This is by design in object oriented programming environment, which is true for Python/Jython and of course the underlying Java.

after
x = Region(find(picture1))

x REPRESENTS an object containing it's specific attributes like x, y, w, h and knowing all the "globally" defined attributes and methods of the class Region., but it is not the object itself: it is only a reference to that object.

so after
r1 = x
r2 = x

r1, r2 and x all REPRESENT the same object (hence the result of Region(find(picture1)), which is called a reference.
so if you change anything in r2, this will show up with r1 and x as well.

BTW: this is sufficient:
x = find(picture1)
now x represents a Match object, but this is a subclass of Region and hence has all the attributes and methods of a Region (called inheritance) plus some more, that are specific for a Match.

The solution: you have to create new objects, if you want to use the new one independently from the other:
x = find(picture1)
r1 = Region(x)
r2 = Region(x)

The Region() is called a constructor and returns a new object created from the given parameters (in this case another Region object).

Now you have 3 different objects, that might have different attributes.

Revision history for this message
rain (851426043-v) said :
#2

Thanks, Rainman
I am learning python now, and incapable with java, infact I am not good at object-oriented programming. I understand you and thanks for you answer.