What is the simplest way to define setter and getter in Python

不羁的心 提交于 2021-01-27 05:01:52

问题


What is the simplest way to define setter and getter in Python? Is there anything like in C#

public int Prop {get; set;}

How to make it like this? Since to write both setter and getter methods for one property like this is just too much work.

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

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

    foo = property(foo_get, foo_set)

Thanks in advance!


回答1:


If the setter and getter do nothing else than accessing an underlying real attribute, then the simplest way of implementing them is not to write setters and getters at all. This is the standard behaviour, and there is no point in writing functions recreating the behaviour the attribute has anyway.

You don't need getters and setters to ensure encapsulation in the case your access logic changes to something different than the standard access mechanics later, since introducing a property won't break your interface.

Python Is Not Java. (And not C# either, for that matter.)




回答2:


Usually you don't write setters/getters at all. There's no point since python doesn't prevent anyone from accessing the attributes directly. However, if you need logic, you can use 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')

You can then use these property methods the same way you would a basic attribute value:

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



回答3:


property is a builtin function in Python, see this link on using them. It works without parens, so you can start with Sven's preference of just using the attribute, and change it to use getters and setters later.



来源:https://stackoverflow.com/questions/9585978/what-is-the-simplest-way-to-define-setter-and-getter-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!