2011-06-16 49 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