Python change self to inherited class

こ雲淡風輕ζ 提交于 2021-01-27 07:32:56

问题


I have this kind of structure:

class Foo:
    def __init__(self, val1):
        self.val1 = val1

    def changeToGoo(self)
        HOW???

class Goo(Foo):
    def __init__(self, val1, val2):
        super(val1)
        self.val2 = val2

a = Foo(1)
a.changeToGoo()

'a' is now an instance of Foo
now i would like to change it to be an instance of Goo, by using the method "changeToGoo", and add the other value.

How can this be done in Python?

I have tried:

self.__class__ = Goo

but when I check:

type(a)

it's still Foo, and not Goo.


回答1:


In Python 2, make Foo inherit from object to make it a new-style class instead:

>>> class Foo(object):
...     def __init__(self, val1):
...         self.val1 = val1
... 
>>> class Goo(Foo):
...     def __init__(self, val1, val2):
...         super(val1)
...         self.val2 = val2
... 
>>> f=Foo(1)
>>> f.__class__
<class '__main__.Foo'>
>>> f.__class__ = Goo
>>> f
<__main__.Goo object at 0x10e9e6cd0>
>>> type(f)
<class '__main__.Goo'>

Now you can change self.__class__. In a changeToGoo() method:

def changeToGoo(self)
    self.__class__ = Goo
    self.val2 = 'some value'

or re-use __init__:

def changeToGoo(self)
    self.__class__ = Goo
    self.__init__(self.val1, 'some value')

This does make your objects somewhat monstrous, in that they change identity. Shapeshifting is rarely a great idea. You may want to rethink your use case.




回答2:


You could do :

def changeToGoo(self, val2):
    return Goo(self.val1, val2)

Then call and assign, adding the extra attribute

a = a.changeToGoo(val2)


来源:https://stackoverflow.com/questions/20722714/python-change-self-to-inherited-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!