我知道這可能是一個愚蠢的問題,但我是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