0

First I have to say that I'm not a professional python programmer,
so I might ask some really stupid questions, please bear with me...

Here is the idea:

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"

Obviously, this is really wrong, but I don't know how how to correct it.

If you can give me some directions, I'll really appreciate it!

4

2 回答 2

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

在这里找到更多关于如何在 python 中使用属性功能的真实世界示例?

于 2013-03-27T03:12:20.800 回答
1

你很接近,只是一些错别字。里面function2应该说myValue

def function2(self):
    print self.myValue

并调用function2添加一组空括号:

foo.function2()
于 2013-03-27T03:05:48.490 回答