Dschoni Dschoni - 14 days ago 5x
Python Question

Assign a class to itself in python

I just want to ask if I can assign an instance of a class to itself in a method.

For example, is the following valid python code?

class O(object):
def __init__(self,value):
self.value = value
def do_something(self):
self = O(1)

Does this lead to any unexpected behaviour?

Obviously, the code can be run. But when I do

A = O(2)

the output is
, when I expect it to be


self is just another local variable. You can assign something else to it just like you can assign something to any variable. To begin with, self points to the same object A points to in your example.

When you then execute self = O(1), that statement rebinds the name self. It was previously referencing an instance of O(), and now you point it to another, different instance of O(). Those two objects are otherwise independent, doing this doesn't make anything else happen. A still references the first instance, self now references a different one.

So assigning O(2) to self doesn't do anything to the previous object that self pointed to. It certainly won't alter the value of the value attribute of that previous object. A still points to the first instance, where the value attribute is pointing to the integer 2.

You may want to read this article on Python names, by Ned Batchelder: Facts and myths about Python names and values, which lays out what happens when you assign something to a Python variable. self is nothing special here.