2013-03-27 91 views
0

首先,我不得不说,我不是一个专业的Python程序员,
所以我可能会问一些很笨的问题,请与我...Python类:存储在类中的变量,并在以后使用它

承担

这里的理念是:

class Foo: 
    def __init__(self): 
     self.myValue = '' 
    def function1(self, something): 
     self.myValue = something 
    def function2(self): 
     print self.myValue 

foo = Foo() 
foo.function1("target") --> I want to store the value "target" in the class and use it later 
foo.function2() --> I want to print out "target" 

显然,这是真的错了,但我不知道如何如何纠正它。

如果你能给我一些指导,我会非常感激!

+1

将'self.Value'更改为'self.myValue'。 – 2013-03-27 03:05:46

+0

你快到了。在所有方法中拼写相同,然后重试。 – SingleNegationElimination 2013-03-27 03:07:11

+0

谢谢,我改变了它。 – amigcamel 2013-03-27 03:09:08

回答

2

您也可以可以尝试看看@property装饰:

class Foo(object): 

    def __init__(self): 
     self._myValue = None 

    @property 
    def myValue(self): 
     print self._myValue 
     return self._myValue 

    @myValue.setter 
    def myValue(self, something): 
     self._myValue = something 

foo = Foo() 
foo.myValue = 10 
foo.myValue 

在此处查找更多内容Real world example about how to use property feature in python?

+0

我在想我写的代码效率不够高...... 也许“装饰者”是我应该深入。 无论如何,非常感谢! – amigcamel 2013-03-27 03:35:18

+0

@OwenLiu欢迎您,请注意,财产可以使用财产方法来实施 – 2013-03-27 03:37:17

1

你很近,只是几个拼写错误。在function2应该说myValue

def function2(self): 
    print self.myValue 

,并呼吁function2添加一个空括号:

foo.function2() 
相关问题