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类,但由于代码结构不可能.谢谢
我强烈怀疑,否定和确信,您的程序设计存在严重错误,需要您执行此操作。在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 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给方法的优点之一。)