如何将(继承)父级转换为子级?

Tom*_*mas 4 python inheritance class

我想知道如何将由某个函数返回的父对象转换为子类.

class A(object):
    def __init__():
        pass

class B(A):
    def functionIneed():
        pass

i = module.getObject()# i will get object that is class A
j = B(i)# this will return exception
j.functionIneed()
Run Code Online (Sandbox Code Playgroud)

我无法改变A类.如果可以的话,我会将classIneed实现到A类,但由于代码结构不可能.谢谢

Ign*_*ams 15

Python不支持"强制转换".您将需要编写,B.__init__()以便它可以采取A并适当地初始化自己.


A. *_*vis 5

我强烈怀疑,否定和确信,您的程序设计存在严重错误,需要您执行此操作。在Python中,与Java不同,很少有问题需要类来解决。如果您需要一个功能,只需定义它:

def function_i_need(a):
     """parameter a: an instance of A"""
     pass # do something with 'a'
Run Code Online (Sandbox Code Playgroud)

但是,如果不能阻止您将函数用作类的方法,则可以通过设置实例的__class__属性来更改实例的类:

>>> class A(object):
...     def __init__(self):
...         pass
... 
>>> class B(A):
...     def functionIneed(self):
...         print 'functionIneed'
... 
>>> a = A()
>>> a.functionIneed()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'functionIneed'
>>> a.__class__ = B
>>> a.functionIneed()
functionIneed
Run Code Online (Sandbox Code Playgroud)

只要B没有__init__方法,这将起作用,因为显然,__init__永远不会调用它。

  • 我只是在博客上写了一个替代方案,该方案可能更好,或者可能更糟。搞怪__class__可能很奇怪,而且可能很危险,但是似乎起作用(至少在CPython中有效)-请参阅[A Python“ Cast Constructor”](http://late.am/post/2012/04/05/ python-cast-constructor) (2认同)
  • @dcrosta您介意将该帖子转为答案吗?你知道,linkrot等 (2认同)

wks*_*rtz 5

你说你想实现这样的事情:

class B(A):
    def functionIneed():
        pass
Run Code Online (Sandbox Code Playgroud)

但实际上你要做的更像是这样的(除非你一开始就打算创建一个静态方法):

class B(A):
    def functionIneed(self):
        pass
Run Code Online (Sandbox Code Playgroud)

然后就可以打电话了B.functionIneed(instance_of_A)(这是必须显式传递self给方法的优点之一