Python 中是否有一个函数与等于运算符执行相同的操作 [英] Is there a function in Python that does the same thing as the equals operator
问题描述
由于我目前对 Python 语法的理解,我遇到了一个问题,我需要将变量设置为一个值但不使用任何运算符.我必须使用函数.
Due to my current understanding of Python's syntax, I have run into an issue where I need to set a variable to a value but without using any operators. I have to use functions.
考虑这个场景
class Senario:
x: str = ''
y: str = ''
set_global_variable(self, set_variable, val: str)
# some verification code and modifications
set_variable(val)
set_x(self, val: str)
self.set_global_variable(setX, val)
set_x(self, val: str)
self.set_global_variable(lambda new_x: self.x = new_x, val)
像这样设置变量的好处是添加新变量不需要为新的setter方法复制粘贴一堆验证码.它更模块化.问题是这样的程序无法运行,因为 lambdas 不能使用运算符.
The benefit of setting variables like this is that adding a new variable doesn't require copying and pasting a bunch of verification code for the new setter method. It is more modular. The problem is that such a program doesn't run because lambdas can't use operators.
错误是 self.set_global_variable(lambda new_x: self.x
--> =
<-- new_x, val)
The error is self.set_global_variable(lambda new_x: self.x
--> =
<-- new_x, val)
这不是正确的语法.为了运行这样的程序,我需要某种与 = 运算符完全相同的 equals 方法.实现方式如下.
It's not the proper syntax. In order to run a program like this, I need some sort of equals method that does the exact same thing as the = operator. The implementation would work as follows.
set_x(self, val: str)
self.set_global_variable(lambda new_x: self.x.equals(new_x), val)
Python 中是否有内置方法可以执行此操作,如果仅适用于字符串?如果没有,是否可以轻松编写方法?可以将一个变量作为输入并将该精确变量设置为一个新值,而不是它的本地副本?
Is there a built-in method in Python to do this, if only for strings? If not, can a method be easily written? One that can take a variable as input and set that exact variable to a new value, and not a local copy of it?
推荐答案
最简单的解决方案可能是使用执行赋值的本地函数,如下所示:
The easiest solution may be to use a local function that performs the assignment, as follows:
def set_x(self, val: str):
def _set_variable(new_x):
self.x = new_x
self.set_global_variable(_set_variable, val)
但是,如果您想使用 lambda 表达式,您可以尝试使用 setattr
python 的内置函数,它满足你的要求:
However, if you want to use a lambda expression, you can try using the setattr
built-in function of python, which does what you asked for:
def set_x(self, val: str):
self.set_global_variable(lambda new_x: setattr(self, "x", new_x), val)
更通用的解决方案可能是将字段名称传递给 set_global_variable
并使用 setattr
执行赋值,如下所示:
A more general solution could be to pass the field name to the set_global_variable
and use setattr
to perform the assignment, as follows:
def set_global_variable(self, variable_name, val):
# some verification code and modifications
setattr(self, variable_name, val)
def set_x(self, val: str):
set_global_variable("x", val)
这篇关于Python 中是否有一个函数与等于运算符执行相同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!