Python将自己更改为继承的类 [英] Python change self to inherited class
问题描述
我有这种结构:
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'现在是Foo的实例
现在,我想通过使用方法"changeToGoo"将其更改为Goo的实例,并添加其他值.
'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.
这如何在Python中完成?
How can this be done in Python?
我尝试过:
self.__class__ = Goo
但是当我检查时:
type(a)
它仍然是Foo,而不是Goo.
it's still Foo, and not Goo.
推荐答案
在Python 2中,使 Foo
从 object
继承,以使其成为新样式的类:
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'>
现在您可以更改 self .__ class __
.在 changeToGoo()
方法中:
Now you can change self.__class__
. In a changeToGoo()
method:
def changeToGoo(self)
self.__class__ = Goo
self.val2 = 'some value'
或重复使用 __ 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.
这篇关于Python将自己更改为继承的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!