我一直在尋找答案,但沒有運氣。我需要有一個子類訪問其父類中屬性的值。如何從Python中的私有類繼承父類屬性?
下面是一個例子:
class myclass:
def __init__(self):
class __firstinternal__:
def __init__(self):
self.second = __secondinternal__()
class __secondinternal__:
def __init__(self):
self.var = myclass.getString()
def getString(self):
return "something"
self.internal = __firstinternal__()
print self.internal.second.var
c = myclass()
Traceback (most recent call last):
File "./inheritest.py", line 19, in <module>
c = myclass()
File "./inheritest.py", line 15, in __init__
self.internal = __firstinternal__()
File "./inheritest.py", line 7, in __init__
self.second = __secondinternal__()
File "./inheritest.py", line 11, in __init__
self.anothervar = myclass.getString()
AttributeError: class myclass has no attribute 'getString'
換句話說,我需要secondinternal繼承方法的getString()從父MyClass的。
我發現如何做到這一點,當類不是一個孩子,但我想保持這兩個類是私人的。
任何想法?
在此先感謝!
您的代碼沒有意義。在'__init__'方法中定義這些類將不會執行任何操作;當方法結束執行時,它們會消失。你有可能在你的代碼中搞砸縮進嗎?你是否試圖將類設置爲外部類的屬性?另外,你爲什麼使用雙下劃線? – BrenBarn 2012-07-22 19:27:52
XY。描述你試圖解決的問題,而不是想象中的愚蠢解決方案。 – 2012-07-22 19:30:21
只要子類使用自己的方法,代碼就可以完美地工作。我的問題是隻有當我需要使用父類的方法。關於雙下劃線 - 嗯,我認爲這是一個孩子班級應該如何定義的... – user1544357 2012-07-22 19:32:20