gpt4 book ai didi

python - 如何在 Python 中创建没有 getter 的 setter?

转载 作者:行者123 更新时间:2023-12-04 13:21:55 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Python class @property: use setter but evade getter?

(4 个回答)


3年前关闭。



class My_Class:
def __init__(self):
self._x = 0

@property
def x(self):
return self._x

@x.setter
def x(self, x):
self._x = x

如果我从上面的代码中删除以下 getter:
@property
def x(self):
return self._x

代码停止工作。如何在没有 getter 的情况下创建 setter?

最佳答案

property函数不必用作装饰器:装饰器可以用作函数:

class My_Class:
def _set_x(self, value):
self._x = value

x = property(fset=_set_x) # now value has only a setter

del _set_x # optional: delete the unneeded setter function

instance = My_Class()
instance.x= 8 # the setter works

print(instance._x) # the "private" value

print(instance.x) # raises: AttributeError: unreadable attribute

关于python - 如何在 Python 中创建没有 getter 的 setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50935795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com