Eric Whale
Eric Whale

Reputation: 137

Why changing object itself through class object doesn't work?

class Cat:
    def func(self):
        self = None

a = Cat()

print(a)

a.func()

print(a)

I thought I would get None with second print function, but I got same object addresses for both prints. Why can't I modify object with class method?

Upvotes: 0

Views: 125

Answers (1)

B. Morris
B. Morris

Reputation: 640

In the class method, self is an argument that becomes part of the local scope. Assigning to any local scope variable only changes the local scope. If you were to assign to an attribute of self such as

self.foo = “Bar”

Then you would modify the object itself.

Furthermore, the object is referenced by a in the calling (global) scope and that reference would prevent destruction of the object.

Put another way, self and a both refer to the same object and assigning self=None only removes one of those references.

Upvotes: 1

Related Questions