Z
Z
zlodiak2019-01-29 23:02:06
Python
zlodiak, 2019-01-29 23:02:06

How do shared references work in classes?

From one class I create two objects like this

class qw:
  a = [1, 2]

x = qw()
y = qw()

print(x.a, y.a)

x.a = x.a.append(3)

print(x.a, y.a)

As a result of execution, I get the following output
[1, 2] [1, 2]
None [1, 2, 3]

Please explain why None is displayed, and then the result of a successful addition?
I understand that.
1. x, y are two separate objects created from a common class
2. x, y are not primitive classes like '1' or 'a'. therefore, in the case of shared references, the variables referring to them must be linked in such a way that when one list changes, the second must also change

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Shyngys Sailaubai, 2019-01-30
@zlodiak

First you need to add an element to the list, then "assign". Since append is a method, xa gets its return value, a strongly typed language would throw an error because append doesn't return anything, but python is fine with "assigning". However , Roman Kitaev said everything correctly.
But if you want to write code in this way, I can please you, syntactic sugar := will appear in python 3.8, you can do this with it.

R
Roman Kitaev, 2019-01-29
@deliro

You didn't read the documentation, right? append added a triple to the list, which all class instances fumble, but append returns nothing. And it's nothing you assign

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question