使用 lambda getter 和 setter 创建属性
我有这样的事情:
class X():
def __init__(self):
self.__name = None
def _process_value(self, value):
# do something
pass
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = self._process_value(value)
name = property(get_name, set_name)
我可以使用 lambda 函数替换 get_name
和 set_name
吗?
我已经尝试过:
name = property(lambda self: self.__name, lambda self, value: self.__name = self.process_value(value))
但编译器不喜欢我的 setter 函数。
I have something like this:
class X():
def __init__(self):
self.__name = None
def _process_value(self, value):
# do something
pass
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = self._process_value(value)
name = property(get_name, set_name)
Can I replace get_name
and set_name
using lambda functions?
I've tried this:
name = property(lambda self: self.__name, lambda self, value: self.__name = self.process_value(value))
but compiler doesn't like my setter function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的问题是 lambda 的主体必须是一个表达式,而赋值是一个语句(Python 中强烈而深刻的区别)。 如果您坚持使用 lambda ,您将遇到许多此类情况并学习解决方法(通常有一个,但并非总是如此),例如,在本例中:
即使用内置的
setattr
(这是一个函数,因此在 lambda 的主体中可以接受)而不是赋值(这是一个语句,因此在 lambda 中是不可接受的”的身体)。您还需要手动对双下划线属性执行名称修改(将
__name
更改为_X__name
,因为您在 X 类中),其中属性名称显示为一个带引号的字符串,因为它必须在setattr
中,因为 Pyhon 编译器只对合适的标识符进行名称修改,而不对字符串文字进行修改。Your problem is that lambda's body must be an expression and assignment is a statement (a strong, deep distinction in Python). If you insist on perpetrating
lambda
s you'll meet many such cases and learn the workarounds (there's usually one, though not always), such as, in this case:i.e. use the built-in
setattr
(which is a function and thus acceptable in alambda
's body) rather than assignment (which is a statement and thus unacceptable in alambda
's body).You also need to perform the name-mangling for the dual-underscore attribute manually (changing
__name
to_X__name
as you're in class X) where the attribute name is presented as a quoted string, as it must be insetattr
, as the Pyhon compiler only does the name mangling in question for suitable identifiers, not for string literals.如果要扩展
list
,还可以使用__setitem__
,如下所示:If you are extending a
list
, you can also use__setitem__
, like this: