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

查看:72
本文介绍了为什么使用“评估"是一种不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的类来轻松存储我的歌曲的数据.

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 代替:

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.

在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.

重新排列了第1点和第4点

EDIT 3: Reordered point 1 and 4

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

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