如何在Python中声明一个以实例作为参数的方法?

2024-06-28 20:08:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这可能是一个愚蠢的问题,但我对Python中的OOP并不熟悉,如果我声明了一个函数def myFunction( b)并将一个对象的实例传递给它,就会得到TypeError:expected string or buffer。在

更具体地说,我有一个下面的代码,我用它来解析一个简单的分子式,并从中生成一个对象。在

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)

谢谢你,托马斯


Tags: 对象intestselfforisdefkeys
1条回答
网友
1楼 · 发布于 2024-06-28 20:08:11

简而言之,您可以将任何对象传递给函数,包括您创建的类的实例。在

在Python中,通常是一个对象。这是Python中的一个概念,因此如果您不熟悉该语言,请花一些时间熟悉它,因为它将帮助您编写更简洁和Python的代码。在

您得到的错误不是由于传递一个类实例对象,而是由另一个函数或操作在代码中的其他地方生成的(请参见其他答案,因为它们似乎在其中),而另一个函数或操作希望对字符串或类似字符串的对象进行操作。例如,您可以通过执行以下操作来生成类似的错误:

>>> a = 2
>>> open(a, 'r')

TypeError: coercing to Unicode: need string or buffer, int found

这里发生错误是因为文件打开函数open要求的是字符串而不是整数。在

网友
2楼 · 发布于 2024-06-28 20:08:11

首先,程序需要包括re模块。在

第二,第4行有一个错误:

for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", SummaryFormula):

应该读

^{pr2}$

summaryFormula中的小写s。在

SummaryFormula表示类的名称,而summaryFormula表示__init__方法的第二个参数(在self之后)。在

第三,行addAtoms = SummaryFormula(b)传递一个SummaryFormula的实例作为参数{}(在脚本test.extend(toExtend)的顶层部分赋值)。在

固定程序应该如下所示:

import re

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()

        # PASS AN APPROPRIATE VALUE HERE!
        addAtoms = SummaryFormula("SOME STRING")

        # 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)

"SOME STRING"替换为预期的字符串文本或字符串变量引用。我不知道这个程序的确切意图,所以我将由其他人来决定这个程序此时应该传递给SummaryFormula的构造函数。在

希望有帮助!在

网友
3楼 · 发布于 2024-06-28 20:08:11

理查德·库克是对的。然而,还有另一个问题:在extend中,你说:

addAtoms = SummaryFormula( b)

因此,SummaryFormula实例被传递到SummaryFormula的__init__方法中。在这里(对前面提到的输入错误进行模化),这个对象被赋予re.finditer

^{pr2}$

函数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.")

相关问题 更多 >