为什么使用“eval"是一种不好的做法? [英] Why is using 'eval' a bad practice?

查看:30
本文介绍了为什么使用“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:

  1. 几乎总有更好的方法来做到这一点
  2. 非常危险和不安全
  3. 使调试变得困难

在您的情况下,您可以使用 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)

在某些情况下,您必须使用 evalexec.但它们很少见.在您的情况下使用 eval 肯定是一种不好的做法.我强调不好的做法,因为 evalexec 经常用在错误的地方.

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.

这篇关于为什么使用“eval"是一种不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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