2011-06-16 52 views
1

我是Python和OOP的新手(& StackOverflow),所以如果這個問題太天真了,不過我似乎無法自行解決它。我剛寫了一個非常簡單的程序,看看OOP是如何工作的,這是我下重現:將值返回給Python中的調用類

from System import * 

class trial(object): 
    def __init__(self, counter): 
     self.counter = counter 

    def passon(self): 
     p = person(self.counter) 
     p.increase() 

class person(object): 
    def __init__(self, counter): 
     self.counter = counter 


    def increase(self): 
     self.counter +=1 
     return self.counter 

我這樣調用該函數:

t = trial(2) 
t.passon() 

我計數器的值期待更新在課堂上試用自動,但是當我鍵入t.counter,但仍返回2。但是,如果我寫的:

p = person(t.counter) 
p.increase() 

然後p.counter變得3.如何增加計數器類審判的價值? 我知道我在這裏犯了一些基本的錯誤,但我會很感激任何幫助。

回答

0

每個類都有一個單獨的屬性counter。如果您想更新trial對象與調用p.increase()的結果計數器,你需要做類似這樣的東西在passon()

def passon(self): 
    p = person(self.counter) 
    self.counter = p.increase() 
+0

謝謝!這非常簡單! – dpsguy 2011-06-17 07:11:15

+0

感謝大家的幫助和快速回復!我認爲隨着學習Python,我會越來越多地使用這個網站。 – dpsguy 2011-06-17 07:13:44

+0

@dpsguy,不客氣!當你收到足夠的答案並且嘗試了它們之後,一定要爲任何對你有幫助的人投票,除了接受你認爲最好的人 - 這只是基本的禮儀! - ) – martineau 2011-06-17 10:11:46

4

Python中的整數是不變的。將trial傳遞給person,然後在保存的trial上增加屬性。

+0

整數的不變性與問題無關。 – martineau 2011-06-16 17:00:21

+0

這是一個過分簡單化,但它並不完全無關;如果它是一個列表並且正在調用「append()」,則不會發生此問題。 – 2011-06-16 17:01:25

1

我相信每個班都有自己的專櫃。修改你的「passon」功能,通過以下方式,你會看到這一點:

def passon(self): 
    p = person(self.counter) 
    print 't', self.counter 
    print 'p', p.counter 
    p.increase() 
    print 'p', p.counter 
    print 't', self.counter 
0

您的問題是否與Python如何處理對象的事 - 有些是不可變的(你不能改變它們,你只能替換它們),有些是可變的(你可以改變它們的內部狀態)。 (如果你知道引用和傳遞值與傳遞引用等int,浮動,字符串和元組就像通過值,(幾乎)其他所有東西都是可變的)。

整數是「不可變的」,這意味着當您對它執行一些操作時,它實際上會返回int的新副本(它也可以是緩存值)。

所以這個:

self.counter = self.counter + 1 

是差不多是這樣

self.counter = new int(counter + 1) # I know, "new" isn't pythonic, 
    #but it is clearer in OOP with the int function. 

那麼,既然self.counter是不是原本傳遞給它同樣的事情,沒有辦法兼得p和t指向同一個對象。

解決方案?進行試用有一個人作爲屬性:

from System import * 

class trial(object): 
    def __init__(self, counter): 
     self.person = person(counter) 

    def passon(self): 
     p.increase() 

class person(object): 
    def __init__(self, counter): 
     self.counter = counter 

    def increase(self): 
     self.counter +=1 
     return self.counter 

t = trial(2); 
t.person # <!-- this is your person object. 
t.passon() 
print(t.person.counter) # 3 
t.passon() 
print(t.person.counter) # 4 
+0

謝謝你清除我的誤解。我認爲所有東西都是通過Python中的引用傳遞的 – dpsguy 2011-06-17 07:10:57