我知道这可能是一个愚蠢的问题,但我是Python中的OOP的新手,如果我声明函数def myFunction(b)
并将对象的实例传递给它,我会得到TypeError:预期的字符串或缓冲区。如何声明一个将实例作为Python参数的方法?
为了更具体一些,我使用下面的代码来解析总结分子式并将其作为对象。
class SummaryFormula:
def __init__(self, summaryFormula):
self.atoms = {}
for atom in re.finditer("([A-Z][a-z]{0,2})(\d*)", summaryFormula):
symbol = atom.group(1)
count = atom.group(2)
def extend(self, b):
# these are the two dictionaries of both molecules
originalFormula = self.atoms.copy()
self.atoms.clear()
addAtoms = SummaryFormula(b)
# and here both dictionaries are merged
for atom in addAtoms.atoms.keys():
if atom in originalFormula.keys():
self.atoms[ atom] = originalFormula[ atom]
self.atoms[ atom] += addAtoms.atoms[ atom]
else:
pass
for atom in originalFormula.keys():
if atom not in self.atoms.keys():
self.atoms[ atom] = originalFormula[ atom]
#this is what works now
test = SummaryFormula("H2CFe2")
test.extend("H5C5") #result is a molecule H7C6Fe2
#this is what I want instead
test = SummaryFormula("H2CFe2")
toExtend = SummaryFormula("H5C5")
test.extend(toExtend)
谢谢,托马斯
你能提供一个代码示例吗? – 2010-09-20 22:25:20
我认为,为了帮助您,我们需要更多的背景信息。 “myFunction”的实际定义是什么?这是一个普通的功能吗?一个方法?什么是堆栈跟踪,除了例外情况? – Dirk 2010-09-20 22:25:28
小心向我们展示函数定义?使用提供的信息我无法说出任何内容。 – dekomote 2010-09-20 22:25:31