我知道这可能是一个愚蠢的问题,但我是 Python 中的 OOP 新手,如果我声明一个函数 def myFunction( b)
并将对象的实例传递给它,我得到类型错误:需要字符串或缓冲区。
更具体地说,我有以下代码,用于解析摘要分子式并从中创建一个对象。
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)
谢谢你,托马斯
最佳答案
理查德·库克是正确的。然而,还有另一个问题:在 extend
中,您说:
addAtoms = SummaryFormula( b)
因此,SummaryFormula 实例被传递到 SummaryFormula 的 __init__
方法中。在这里(以前面提到的拼写错误为模),这个对象被赋予re.finditer
:
for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula)
函数re.finditer
需要一个字符串;它不知道如何处理 SummaryFormula
实例。
有几种方法可以解决这个问题。最简单的方法是在尝试创建一个 SummaryFormula 实例之前检查您是否已经有一个 SummaryFormula 实例:
if isinstance(b, SummaryFormula):
addAtoms = b
else if isinstance(b, str):
addAtoms = SummaryFormula(b)
else:
raise TypeError("Expected a SummaryFormula or equivalent string.")
关于python - 如何在 Python 中声明一个将实例作为参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3755948/