When passing objects to functions, only the reference is copied, not the object itself. If the method has access to attributes of the object, it can change the object. This change is preserved after the method returns.
class Person:
name = ""
def setName(n, o):
o.name = n
p1 = Person()
p2 = Person()
setName("John", p1)
setName("Tom", p2)
print(p1.name)
print(p2.name)
John
Tom
This code defines a class named Person
with a single attribute, name
. The class also defines a method setName
that takes two arguments: n
and o
. The method sets the name
attribute of the Person
object passed as o
to the value of n
.
Two objects, p1
and p2
, are created from the Person
class. The setName
method is then called twice, once for each object, with different values for the n
parameter, “John” and “Tom”, respectively.
This demonstrates that the setName
method can be used to set the name
attribute for multiple instances of the Person
class.