這是你如何能做到這一點:
class First:
def __init__(self):
self.text = "This is a text in First class"
self.second = Second(self)
class Second:
def __init__(self, first):
self.first = first
print "How to show self.text from First?"
print self.first.text
對象是知道對方以這種方式,並使用對方的屬性,我擔心,有可能違反law of demeter或使其難以區分彼此。 爲了區分它們對於編寫「好」類非常重要。 所以小心處理!
其他的解決方案:通過文字:
class First:
def __init__(self):
self.text = "This is a text in First class"
self.second = Second(self.text)
class Second:
def __init__(self, text):
self.text = text
print "How to show self.text from First?"
print self.text
這也是相當確定。 我比第一個解決方案更喜歡它。 但是當有更多的參數來的時候,text1,text2,text3,...比這個可能是一個新的對象。
class First(object):
@property
def text(self):
"get text from self.second"
return self.second.text
def __init__(self):
self.second = Second("This is a text in First class")
print self.text
class Second:
def __init__(self, text):
self.text = text
print "How to show self.text from First?"
print self.text
我覺得這對於同步文本來說也是一個不錯的解決方案。 但我想不出一個我真正需要它的例子。
如果我理解你的問題的權利,你希望繼承從第一 –
1)你的實際問題是什麼?對於任意類,任何解決方案都可以。 2)考慮對象,而不是類。 –
@AdityaSihag - 我想訪問來自First in Seconds的屬性和方法。例如,假設Second中的某個動作需要在First中調用回調。 – ov1d1u