Search code examples
pythoninstanceself

Overwirting an instance (overwrite/copy self) in python


In the line after elif I assign the argument text to self. A vain attempt to overwrite/copy the current instance.

class Someclass(object):
    def __init__(self, text):
        if type(text) == type(""):
            self._get_lines(text)
            self._parse_stats()
        elif type(text) == type(self):
            self = text
        else:
            raise TypeError()

self is assigned, but only in the scope of init()

Is it possible to copy an instance in this way (or similair), or do I need to go through and copy each instance variable to a new instance. Still how do I return it?


Solution

  • overwriting self does not affect the instance itself. you can return different object from constructor by overriding __new__.

    def SomeClass(object):
        def __new__(cls, text):
            if isinstance(text, SomeClass):
                #return a copy of text. maybe..
                return copy.copy(text) 
            elif isinstance(text, basestring):
                #return a new instance. __init__ will handle the rest
                return super(SomeClass, cls).__new__(text)  
            else:
                raise TypeError
    
        def __init__(self, text):
            ....