Why can’t I perform an action like the following:
class Test(object):
def __init__(self):
self = 5
t = Test()
print t
I would expect it to print 5 since we’re overwriting the instance with it, but instead it doesn’t do anything at all. Doesn’t even throw an error. Just ignores the assignment.
I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can’t.
Update: I now understand why it doesn’t work, but I’d still like to know if there is any way of replacing an instance from within the instance.
Any simple assignment to any argument of any function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. “No special case is special enough to break the rules”, as the Zen of Python says!-)
So, far from it being odd (that simply=assigning to a specific argument in a specific function has no externally visible effect whatsoever), it would be utterly astonishing if this specific case worked in any other way, just because of the names of the function and argument in question.
Should you ever want to make a class that constructs an object of a different type than itself, such behavior is of course quite possible — but it’s obtained by overriding the special method
__new__, not__init__:This does emit
5. The__new__/__init__behavior in Python is an example of the “two-step construction” design pattern: the “constructor” proper is__new__(it builds and returns a (normally uninitialized) object (normally a new one of the type/class in question);__init__is the “initializer” which properly initializes the new object.This allows, for example, the construction of objects that are immutable once constructed: in this case everything must be done in
__new__, before the immutable object is constructed, since, given that the object is immutable,__init__cannot mutate it in order to initialize it.