使用Lambda getter和setter创建属性 [英] Create properties using lambda getter and setter

查看:96
本文介绍了使用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_nameset_name吗?

Can I replace get_name and set_name using lambda functions?

我已经尝试过了:

name = property(lambda self: self.__name, lambda self, value: self.__name = self.process_value(value))

但是编译器不喜欢我的setter函数.

but compiler doesn't like my setter function.

推荐答案

您的问题是lambda的主体必须是一个表达式,赋值是一个语句(在Python中有很深的区别).如果您坚持使用lambda,则会遇到许多此类情况并了解变通方法(通常是一种,尽管并非总是如此),例如在这种情况下:

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 lambdas you'll meet many such cases and learn the workarounds (there's usually one, though not always), such as, in this case:

name = property(lambda self: self.__name, 
                lambda self, value: setattr(self, 
                                            '_X__name',
                                            self.process_value(value)))

即使用内置的setattr(这是一个函数,因此在lambda的主体中是可接受的),而不是赋值(这是一个语句,因此在lambda的主体中是不可接受的).

i.e. use the built-in setattr (which is a function and thus acceptable in a lambda's body) rather than assignment (which is a statement and thus unacceptable in a lambda's body).

您还需要手动执行对double-underscore属性的名称处理(当您在类X中时,将__name更改为_X__name),其中属性名称以带引号的字符串表示,因为它必须在setattr中,因为Pyhon编译器仅对适当的标识符(而不是字符串文字)进行有问题的名称修改.

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 in setattr, as the Pyhon compiler only does the name mangling in question for suitable identifiers, not for string literals.

这篇关于使用Lambda getter和setter创建属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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