简体   繁体   English

在lambda函数中自动传递自我?

[英]Pass self automatically in lambda function?

Is there a way to automatically pass self to a lambda function in a class?有没有办法自动将 self 传递给类中的 lambda 函数? I know I can pass self in the __init__ function but then I'm redefining token_functions for every instance of Parser .我知道我可以在__init__函数中传递 self 但随后我要为Parser的每个实例重新定义token_functions token_functions never changes so this seems quite inefficient. token_functions永远不会改变,所以这看起来效率很低。 Is there a better way to do this?有一个更好的方法吗?

class Parser:
    token_functions = {r'\n': lambda: Parser.new_line(self)}

    def __init__(self):
        self.line_number = 0
        Parser.token_functions[r'\n']()
    
    def new_line(self):
        self.line_number += 1
        print(self.line_number)
    
Parser()

No. The function created by the lambda expression is not a class attribute, so the descriptor protocol is not triggered.不会。lambda 表达式创建的函数不是类属性,因此不会触发描述符协议。

You could call its __get__ method directly, eg Parser.token_functions[r'\n'].__get__(self, type(self))() , but you probably don't want to be dealing with the low-level machinery directly.可以直接调用它的__get__方法,例如Parser.token_functions[r'\n'].__get__(self, type(self))() ,但您可能不想直接处理低级机器。

Just define the function to accept an object with a new_line method as an explicit argument, and pass self when the time comes.只需定义函数以接受带有new_line方法的对象作为显式参数,并在时机成熟时传递self

class Parser:
    token_functions = {r'\n': lambda obj: obj.new_line()}

    def __init__(self):
        self.line_number = 0
        Parser.token_functions[r'\n'](self)
    
    def new_line(self):
        self.line_number += 1
        print(self.line_number)

The operator module provides a methodcaller function to replace this use of a lambda expression. operator模块提供了一个methodcaller函数来替换对 lambda 表达式的这种使用。

token_functions = {'\n': operator.methodcaller('new_line')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM