Convert a BaseClass object into a SubClass object idiomatically?

前端 未结 2 1871
终归单人心
终归单人心 2020-12-16 20:45

There is a base class Base and a subclass Special.

class Base(object):
    def __init__(self, name):
        self.name = name
    d         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 21:20

    actually you can, but I don't think you should. instead of typecasting python has duck-typing to solve this kind of situation.

    anyway, here's the code:

    >>> 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?"
    

提交回复
热议问题