为什么使用“eval"是一种不好的做法?
我正在使用以下类来轻松存储我的歌曲数据.
I am using the following class to easily store data of my songs.
class Song:
"""The class to store the details of each song"""
attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')
def __init__(self):
for att in self.attsToStore:
exec 'self.%s=None'%(att.lower()) in locals()
def setDetail(self, key, val):
if key in self.attsToStore:
exec 'self.%s=val'%(key.lower()) in locals()
我觉得这比写出一个 if/else
块更可扩展.然而, eval
似乎被认为是一种不好的做法,使用起来不安全.如果是这样,谁能向我解释原因并向我展示定义上述类的更好方法?
I feel that this is just much more extensible than writing out an if/else
block. However, eval
seems to be considered a bad practice and unsafe to use. If so, can anyone explain to me why and show me a better way of defining the above class?
是的,使用 eval
是一种不好的做法.仅举几个原因:
Yes, using eval
is a bad practice. Just to name a few reasons:
- 几乎总有更好的方法来做到这一点
- 非常危险和不安全
- 使调试变得困难
- 慢
在您的情况下,您可以使用 setattr 代替:
In your case you can use setattr instead:
class Song:
"""The class to store the details of each song"""
attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')
def __init__(self):
for att in self.attsToStore:
setattr(self, att.lower(), None)
def setDetail(self, key, val):
if key in self.attsToStore:
setattr(self, key.lower(), val)
在某些情况下,您必须使用 eval
或 exec
.但它们很少见.在您的情况下使用 eval
肯定是一种不好的做法.我强调不好的做法,因为 eval
和 exec
经常用在错误的地方.
There are some cases where you have to use eval
or exec
. But they are rare. Using eval
in your case is a bad practice for sure. I'm emphasizing on bad practice because eval
and exec
are frequently used in the wrong place.
回复评论:
看起来有些人不同意 eval
在 OP 案例中非常危险和不安全".对于这种特定情况,这可能是正确的,但在一般情况下并非如此.这个问题很笼统,我列出的原因也适用于一般情况.
It looks like some disagree that eval
is 'very dangerous and insecure' in the OP case. That might be true for this specific case but not in general. The question was general and the reasons I listed are true for the general case as well.