你可以通过定义一个备用构造函数并重新分配实例的
__class__
属性来实现这一点。
class Base(object):
def __init__(self, name):
self.name = name
def greet(self):
return 'Hello %s' % self.name
@classmethod
def alt_constructor(cls, *args, **kwargs):
obj = cls(*args, **kwargs)
obj.__class__ = Special
return obj
class Special(Base):
def __init__(self, name):
super(Special, self).__init__(name)
def rhyme(self):
return 'Hi %s! How are you? Fine, thanks. What about you?' % self.name
>>> s = Base.alt_constructor("test")
>>> print s.rhyme()
Hi test! How are you? Fine, thanks. What about you?
编辑:
将构造函数从Special
移动到Base
。
如果您无法修改Base
类,则可以向Special
添加一个classmethod,该方法将更改传递给它的任何对象的类。
class Base(object):
def __init__(self, name):
self.name = name
def greet(self):
return 'Hello %s' % self.name
class Special(Base):
def __init__(self, name):
super(Special, self).__init__(name)
def rhyme(self):
return 'Hi %s! How are you? Fine, thanks. What about you?' % self.name
@classmethod
def convert_to_special(cls, obj):
obj.__class__ = Special
>>> b = Base("test")
>>> print type(b)
<class '__main__.Base'>
>>> Special.convert_to_special(b)
>>> print type(b)
<class '__main__.Special'>
更通用的解决方案是创建一个可以添加到任何类的Mixin。
class ConverterMixin(object):
@classmethod
def convert_to_class(cls, obj):
obj.__class__ = cls
class Special(ConverterMixin, Base):
def __init__(self, name):
super(Special, self).__init__(name)
def rhyme(self):
return 'Hi %s! How are you? Fine, thanks. What about you?' % self.name
>>> b = Base("test")
>>> print type(b)
<class '__main__.Base'>
>>> Special.convert_to_class(b)
>>> print type(b)
<class '__main__.Special'>