Python 新手:使用 eval() 为 self.variable 赋值
Python Newbie: using eval() to assign a value to a self.variable
我是 Python 的新手,我有一个 class 有很多变量,像这样:
class trash:
def __init__(self):
self.var1=1
self.var2=1
self.var3=1
...
def replaceByTwo(self, var_name)
self.eval(var_name) = 2
但是当我调用 replaceByTwo 时,我收到了这个:
AttributeError: 'trash' object has no attribute 'eval'
有谁知道如何解决这个问题?
谢谢!
您收到的错误是因为您正在尝试调用 self.eval()
,但 eval 是一个全局函数,而不是您的实例的成员。
无论如何,对于您想做的事情,例如按名称设置成员/属性,您应该使用 setattr()
.
eval
是 Python 类 的内置方法而不是默认方法。但是你要的是setattr
:
def replaceByTwo(self, var_name):
setattr(self, var_name, 2)
试用:
>>> t = trash()
>>> print(t.var2)
1
>>> t.replaceByTwo('var2')
>>> print(t.var2)
2
我是 Python 的新手,我有一个 class 有很多变量,像这样:
class trash:
def __init__(self):
self.var1=1
self.var2=1
self.var3=1
...
def replaceByTwo(self, var_name)
self.eval(var_name) = 2
但是当我调用 replaceByTwo 时,我收到了这个:
AttributeError: 'trash' object has no attribute 'eval'
有谁知道如何解决这个问题? 谢谢!
您收到的错误是因为您正在尝试调用 self.eval()
,但 eval 是一个全局函数,而不是您的实例的成员。
无论如何,对于您想做的事情,例如按名称设置成员/属性,您应该使用 setattr()
.
eval
是 Python 类 的内置方法而不是默认方法。但是你要的是setattr
:
def replaceByTwo(self, var_name):
setattr(self, var_name, 2)
试用:
>>> t = trash()
>>> print(t.var2)
1
>>> t.replaceByTwo('var2')
>>> print(t.var2)
2