Python-使用getter和setter的pythonic方法是什么?

我这样做:

def set_property(property,value):  

def get_property(property):

要么

object.property = value  

value = object.property

我是Python的新手,所以我仍在探索语法,并且我想在此方面提供一些建议。

回答:

试试这个: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

以上是 Python-使用getter和setter的pythonic方法是什么? 的全部内容, 来源链接: utcz.com/qa/425865.html

回到顶部