Skip to main content
 首页 » 编程设计

将自身更改为列表的python函数

2025年05月04日14zhenyulu

所以我正在从事一个有趣的化学项目,并且我有一个从文本文件初始化列表的函数。我想做的是让函数用一个列表替换它自己。所以这是我的第一次尝试,随机会或不会工作,我不知道为什么:

def periodicTable(): 
    global periodicTable 
    tableAtoms = open('/Users/username/Dropbox/Python/Chem Project/atoms.csv','r') 
    listAtoms = tableAtoms.readlines() 
    tableAtoms.close() 
    del listAtoms[0] 
    atoms = [] 
    for atom in listAtoms: 
        atom = atom.split(',') 
        atoms.append(Atom(*atom)) 
    periodicTable = atoms 

它以这种方式被调用:

def findAtomBySymbol(symbol): 
    try: 
        periodicTable() 
    except: 
        pass 
    for atom in periodicTable: 
        if atom.symbol == symbol: 
            return atom 
    return None 

有没有办法让它工作?

请您参考如下方法:

不要那样做。正确的做法是使用装饰器来确保函数只执行一次并缓存返回值:

def cachedfunction(f): 
    cache = [] 
    def deco(*args, **kwargs): 
        if cache: 
            return cache[0] 
        result = f(*args, **kwargs) 
        cache.append(result) 
        return result 
    return deco 
 
@cachedfunction 
def periodicTable(): 
    #etc 

也就是说,没有什么能阻止您在调用函数后替换函数本身,因此您的方法通常应该可行。我认为它没有的原因是因为在将结果分配给 periodicTable 之前抛出异常,因此它永远不会被替换。尝试删除 try/except block 或将毯子 except 替换为 except TypeError 以查看到底发生了什么。