0

在 C-ish 语言中,我会使用 getter/setter 方法/函数来掩盖数据存储细节,例如:

int getFoo();
void setFoo(int value);

我有一些 Python 可以:

class MyClass:
    def Foo(self):
        ...magic to access foo...
        return value

为 Foo 编写/命名设置器的正确方法是什么?我确信它比语言功能更成语,但我不确定什么是常见的。也许我需要重命名Foo()getFoo()匹配它setFoo()。我想这没关系,如果这是通常所做的。

4

3 回答 3

2

你可以使用一个属性。这是直接从文档中提取的:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

现在你可以做...

c = C()
c.x = "a"
print c.x
>>> "a"
del c.x

请记住,在 Python 3 之前的 Python 版本(例如,Python 2.7)中,您需要确保您的对象是新样式的类(它必须派生自object)才能支持这样的属性。当然,无论如何,您可能应该为所有课程使用新型课程...

于 2012-08-15T15:13:05.680 回答
1

使用内置属性函数:

class MyClass:

    def __init__(self):
        self._value = 'Initialize self._value with some value or None'        

    def get_foo(self):
        ...magic to access foo...
        return self._value

    def set_foo(self, value):
        ... magic processing for value ...
        self._value = value

    foo = property(get_foo, set_foo)

现在您可以像这样使用访问它:

inst = MyClass()
inst.foo = 'Some value'
print inst.foo

它将打印:

'一些价值'

于 2012-08-15T15:16:43.100 回答
0

通常,您不需要在 Python 中使用 getter 和 setter。

但是,如果您想将过程的结果公开为属性,则可以使用@property装饰器

class MyClass:
    @property
    def foo(self):
        # operation
        return value

    @foo.setter
    def foo(self, value):
        # operation storing value

仅将 的值存储foo在属性中更为常见。这可以在__init__实例初始化程序中计算:

class MyClass:
    def __init__(self):
        self.foo = someCalculationDeterminingFoo()
于 2012-08-15T15:12:49.043 回答