使用 getter 和 setter 的 Pythonic 方式是什么? [英] What's the pythonic way to use getters and setters?

查看:32
本文介绍了使用 getter 和 setter 的 Pythonic 方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这样做的:

def set_property(property,value):  
def get_property(property):  

object.property = value  
value = object.property

我是 Python 的新手,所以我仍在探索语法,我想在这方面得到一些建议.

I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this.

推荐答案

试试这个:Python 属性

示例代码为:

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

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

    @x.setter
    def x(self, value):
        print("setter of x called")
        self._x = value

    @x.deleter
    def x(self):
        print("deleter of x called")
        del self._x


c = C()
c.x = 'foo'  # setter called
foo = c.x    # getter called
del c.x      # deleter called

这篇关于使用 getter 和 setter 的 Pythonic 方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆