[問題] Python的class要如何互相串接?

作者: chchan1111 (123)   2018-03-24 00:53:51
各位前輩大家好
不好意思不知道標題這樣描述對不對
主要問題是說 如果我今天在class A裡面實體化 class B,有沒有辦法用class B去修改
class A裡的變數或用class A裡的function
例如C#的方式是像這樣:
class A
{
B son = new B();
son.father=this
}
class B
{
A father = null;
}
這樣如果A裡有個變數叫apple
就可以在class B裡面用father.apple=??? 來直接修改他的值
請問Python有類似的方法嗎?
找了蠻久的不過目前還沒看到QQ
作者: bibo9901 (function(){})()   2018-03-24 01:05:00
不就直接賦值給一個變數就好self.son = B(); self.son.father = selfpython 沒有宣告, 你隨便給一個值就行. 甚至不給也行
作者: vfgce (小兵)   2018-03-24 11:47:00
你這樣做,class B每次都得檢查father是不是None或null..才能調用father的方法或屬性..為何不直接在B初始方法就傳入一個A實體當father?class a __init__(self): self.son = B(self)class B __init__(self,father) self.father=father

Links booklink

Contact Us: admin [ a t ] ucptt.com