Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中覆盖实例(覆盖/复制自身)_Python_Instance_Self - Fatal编程技术网

在python中覆盖实例(覆盖/复制自身)

在python中覆盖实例(覆盖/复制自身),python,instance,self,Python,Instance,Self,在elif之后的行中,我将参数text分配给self。试图覆盖/复制当前实例的徒劳尝试 class Someclass(object): def __init__(self, text): if type(text) == type(""): self._get_lines(text) self._parse_stats() elif type(text) == type(self):

elif之后的行中,我将参数text分配给self。试图覆盖/复制当前实例的徒劳尝试

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已分配,但仅在init的范围内()


是否可以通过这种方式(或类似方式)复制实例,或者是否需要遍历并将每个实例变量复制到新实例。仍然要如何返回它?

覆盖
self
不会影响实例本身。您可以通过重写
\uuuu new\uuuu
从构造函数返回不同的对象

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):
        ....