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

查看:110
本文介绍了使用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.

推荐答案

请尝试以下操作:示例代码为:

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天全站免登陆