D
D
Dasha_PROgrammer2021-06-27 07:55:43
Python
Dasha_PROgrammer, 2021-06-27 07:55:43

Is it possible to equate references of both objects in OOP?

I have a class and 2 instances of it.
How to check that the references to these 2 objects are different and can they be made the same?

class Game:
    def __init__(self, player):
        self.player = player

    def sysout(self, position):
        print(f"{self.player} на {position} месте")


player1 = Game('петя')
player1.sysout(1)

player2 = Game('Вася')
player2.sysout(2)

print(id(player1), id(player2))
player1 = player2
print(id(player1), id(player2))
# после строки player1=player2 объекты стали равны, а ссылки на эти объекты остались прежними, то есть всё равно разные?
# как это проверить?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kamenyuga, 2021-06-27
@Dasha_PROgrammer

What is the sameness that needs to be obtained and / or checked?
In Python, variables and objects are like the keys and values ​​of a dictionary. Objects work directly in the code, and variables point to these objects and allow you to access them. One object can be referenced by many variables. Objects themselves can refer to other objects, for example, a list stores links to its contents. And most importantly, the object lives as long as at least someone refers to it, and when the references become 0, the object is destroyed by the garbage collector.
So the following happened in the above code - initially 2 objects were created (Petya and Vasya), then both variables began to point to Vasya, and Petya was destroyed. There is only 1 object and 2 references to it.
Instead of assigning one object to both variables, it was possible to make the value self.playerequal in them. Then it would be two different objects with exactly the same behavior - by the way, this is one of the approaches to creating singletons in python.
To fully understand what is happening here, you can read a good python tutorial, and then googling more about the garbage collector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question