我正在使用以下课程轻松存储我的歌曲数据.
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()
Run Code Online (Sandbox Code Playgroud)
我觉得这比写出一个if/else块更具可扩展性.但是,eval似乎被认为是一种不良做法并且使用起来不安全.如果是这样,任何人都可以向我解释为什么并告诉我一个更好的方法来定义上面的类?
eval()Python中有一个函数我在玩游戏时偶然发现.我不能想到需要这个功能的情况,除了可能是语法糖.谁能举个例子?
我正在尝试根据匹配结果将名称更改为变量...
inds_EUR = [whatever]
inds_AFR = [foo]
inds_ASN = [other]
pop=inds_EUR ##imagine this is the case
for pp in ('EUR', 'AFR', 'ASN'):
if pp in pop:
paap='inds_'+str(pp)
break
foos=eval(paap)
Run Code Online (Sandbox Code Playgroud)
我正在尝试的是将"foos"设置为传递给此表达式的列表
matches = [item for item in inds_vcf if item in foos]
Run Code Online (Sandbox Code Playgroud)
它工作,但不知道使用这个eval()表达式是否危险,这里可能是因为它使用vars()我是以正确的方式做到的吗?
提前致谢,
佩希