10

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

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()

我无法更改 A 类。如果可以的话,我会将 functionIneed 实现为 A 类,但由于代码结构,这是不可能的。

4

6 回答 6

23

Python 不支持“强制转换”。您将需要编写B.__init__()以便它可以接受A并适当地初始化自己。

于 2012-04-05T14:24:31.043 回答
8

I have a strong suspicion, nay, conviction, that there is something horribly wrong with your program design that it requires you to do this. In Python, unlike Java, very few problems require classes to solve. If there's a function you need, simply define it:

def function_i_need(a):
     """parameter a: an instance of A"""
     pass # do something with 'a'

However, if I cannot dissuade you from making your function a method of the class, you can change an instance's class by setting its __class__ attribute:

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

This will work as long as B has no __init__ method, since, obviously, that __init__ will never be called.

于 2012-04-05T14:28:28.350 回答
3

你说你想实现这样的东西:

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

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

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

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

于 2012-04-05T19:34:52.713 回答
0

您没有正确定义您的类。应该是这样的:

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

class B(A):
    def __init__(self):
        super(B,self).__init__()

    def functionIneed(self):
        pass

那么你也能

j=B()
j.fuctionIneed()

正如预期的那样

你忘了参考ins

于 2018-04-13T15:18:13.917 回答
0

只是跳出框框思考:

与其使用您想要的功能的新类,不如将功能添加到您已经拥有的类或实例中?

在将方法添加到现有对象实例 中有很好的描述

于 2021-10-21T20:47:25.640 回答
-1

怎么样:

i = module.getObject() # i will get object that is class A
try:
    i.functionIneed()
except AttributeError:
    # handle case when u have a bad object

阅读鸭子打字。

于 2012-04-10T17:13:03.080 回答