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?
self.value = value
self = O(1)
A = O(2)
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.
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
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.