9

有一个基类Base和一个子类Special

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

我怎样才能把一个实例Base变成一个实例Special?目前我有一个classmethod定义Special,只是重新分配__dict__

class Special(Base):
    ...
    @classmethod
    def from_base(cls, baseobj):
        special = Special()
        special.__dict__ = baseobj.__dict__
        return special

这是惯用语吗?如果不是,那会是什么?

PS 一个示例场景:基类是一些默认实现。在野外,您可能会找到基类的对象。现在在某些项目中,基类已成为子类,并且已将特殊方法添加到子类中。现在您主要还是使用基类对象,但有时您会想要“升级”到特殊类,因为您需要访问一些方法。

4

2 回答 2

8

您可以通过定义备用构造函数并重新分配实例的__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这将改变传递给它的任何对象的类。

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'>
于 2013-08-02T15:02:13.587 回答
2

实际上你可以,但我认为你不应该。而不是类型转换,python 有鸭子类型来解决这种情况。

无论如何,这是代码:

>>> base = Base("I'm a base!")
>>> hasattr(base, 'rhyme')
False
>>> base.__class__ = Special
>>> hasattr(base, 'rhyme')
True
>>> base.rhyme()
"Hi I'm a base!! How are you? Fine, thanks. What about you?"
于 2013-08-02T15:03:27.597 回答