如何在 Python 中获取/设置方法(特别是 Trac)



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

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

我有一些Python可以:

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

为 Foo 编写/命名二传手的正确方法是什么? 我确定它比语言功能更成语,但我不确定什么是共同的。 也许我需要将Foo()重命名为 getFoo() 并将其与 setFoo() 匹配. 我想如果这是通常的做法,那没关系。

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

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 ),以便支持这样的属性。当然,无论如何,您可能应该为所有类使用新式类......

使用内置属性函数:

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

它将打印:

"一些价值"

一般来说,

你不需要在 Python 中使用 getter 和 setters。

但是,如果要将过程的结果公开为属性,则可以使用@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()

相关内容

最新更新