在Python中定义setter和getter的最简单方法是什么

时间:2012-03-06 14:50:18

标签: python setter getter

在Python中定义setter和getter的最简单方法是什么? C#

中有类似的东西吗?
public int Prop {get; set;}

如何制作这样的?既然要为这样的属性编写setter和getter方法就太多了。

class MyClass():
    def foo_get(self):
        return self._foo

    def foo_set(self, val):
        self._foo = val

    foo = property(foo_get, foo_set)

提前致谢!

3 个答案:

答案 0 :(得分:17)

如果setter和getter除了访问底层的真实属性之外别无其他,那么实现它们的最简单方法就是不要编写setter和getter。这是标准行为,编写函数重建属性所具有的行为毫无意义。

如果您的访问逻辑在以后更改为与标准访问机制不同的内容,则不需要getter和setter来确保封装,因为引入属性不会破坏您的界面。

Python Is Not Java.(而不是C#,就此而言。)

答案 1 :(得分:9)

通常你根本不写setters / getters。没有必要,因为python不会阻止任何人直接访问属性。但是,如果您需要逻辑,则可以使用propertys

class Foo(object):
    def __init__(self, db):
        self.db = db

    @property
    def x(self):
        db.get('x')

    @x.setter
    def x(self, value):
        db.set('x', value)

    @x.deleter
    def x(self):
        db.delete('x')

然后,您可以像使用基本属性值一样使用这些属性方法:

foo = Foo(db)
foo.x
foo.x = 'bar'
del foo.x

答案 2 :(得分:1)

property是Python中的builtin function,有关使用它们的信息,请参阅this link。它没有parens,所以你可以从Sven的偏好开始,只使用属性,然后将其改为使用getter和setter。