2012-04-05 80 views
4

我想知道如何將由某個函數返回的父對象轉換爲子類。如何將父類轉換(繼承)到子類?

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類,但由於它的代碼結構是不可能的。 謝謝

回答

12

Python不支持「投射」。您需要編寫B.__init__(),以便它可以採取A並適當地進行初始化。

+1

這是比我的更好的答案。 – 2012-04-05 14:28:47

3

我有一個強烈的懷疑,不,確信,你的程序設計有一些可怕的錯誤,它需要你這樣做。在Python中,與Java不同,很少有問題需要類來解決。如果您需要的功能,簡單地定義它:

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

但是,如果我不能讓你的函數類的方法勸阻你,你可以通過設置__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 

只要B沒有__init__方法,這將工作,因爲很明顯,__init__將永遠不會被調用。

+1

我剛剛在博客中提出了一個可能更好或者可能更糟的替代解決方案。用'__class__'搞亂是奇怪的,可能是危險的,但似乎可行(至少在CPython中) - 請參見[Python的「構造函數」](http://late.am/post/2012/04/05/ a-python-cast-constructor) – dcrosta 2012-04-05 14:52:34

+1

@dcrosta你介意把這個帖子轉換成答案嗎?你知道,linkrot等 – 2013-04-09 15:11:15

2

你說你想實現這樣的事情:

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

但實際上你會做更多的東西像這樣的(除非你本來打算在首位作出classstatic法) :

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

然後你可以撥打B.functionIneed(instance_of_A)。 (這是具有的優勢之一pass self explicitly to methods.

0

如何:

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

閱讀上鴨打字。