使用类、方法定义变量

2024-05-29 04:11:11 发布

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

我有一个数据库里保存着许多化学物质和相应的数据,我如何返回一个特定的化学物质,和它的数据,通过它的公式,例如o2。你知道吗

class SourceNotDefinedException(Exception):
def __init__(self, message):
    super(SourceNotDefinedException, self).__init__(message)

class tvorechoObject(object):
"""The class stores a pair of objects, "tv" objects, and "echo" objects. They are accessed
simply by doing .tv, or .echo. If it does not exist, it will fall back to the other variable.
If neither are present, it returns None."""
def __init__(self, echo=None, tv=None):
    self.tv = tv
    self.echo = echo

def __repr__(self):
    return str({"echo": self.echo, "tv": self.tv}) # Returns the respective strings

def __getattribute__(self, item):
    """Altered __getattribute__() function to return the alternative of .echo / .tv if the requested
    attribute is None."""

    if item in ["echo", "tv"]:    
        if object.__getattribute__(self,"echo") is None: # Echo data not present
            return object.__getattribute__(self,"tv") # Select TV data
        elif object.__getattribute__(self,"tv") is None: # TV data not present
            return object.__getattribute__(self,"echo") # Select Echo data
        else:
            return object.__getattribute__(self,item) # Return all data

    else:
        return object.__getattribute__(self,item) # Return all data


class Chemical(object):
    def __init__(self, inputLine, sourceType=None):
        self.chemicalName = TVorEchoObject()    
        self.mass = TVorEchoObject()
        self.charge = TVorEchoObject()


        self.readIn(inputLine, sourceType=sourceType)

def readIn(self, inputLine, sourceType=None):

    if sourceType.lower() == "echo": # Parsed chemical line for Echo format 


        chemicalName            = inputLine.split(":")[0].strip()
        mass               = inputLine.split(":")[1].split(";")[0].strip()
        charge                 = inputLine.split(";")[1].split("]")[0].strip()


        # Store the objects
        self.chemicalName.echo = chemicalName
        self.mass.echo = mass
        self.charge.echo = charge


    elif sourceType.lower() == "tv": # Parsed chemical line for TV format


        chemicalName          = inputLine.split(":")[0].strip()
        charge               = inputLine.split(":")[1].split(";")[0].strip()
        mass                 = inputLine.split(";")[1].split("&")[0].strip()


        # Store the objects
        self.chemicalName.tv = chemicalName
        self.charge.tv = charge
        self.mass.tv  = molecularWeight

    else:
        raise SourceNotDefinedException(sourceType + " is not a valid `sourceType`") # Otherwise print 


def toDict(self, priority="echo"):
    """Returns a dictionary of all the variables, in the form {"mass":<>, "charge":<>, ...}.
    Design used is to be passed into the Echo and TV style line format statements."""
    if priority in ["echo", "tv"]:
    # Creating the dictionary by a large, to avoid repeated text
        return dict([(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))
            for attributeName in ["chemicalName", "mass", "charge"]])
    else:
        raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print






from ParseClasses import Chemical
allChemical = []
chemicalFiles = ("/home/temp.txt")


for fileName in chemicalFiles:
    with open(fileName) as sourceFile:
        for line in sourceFile:
        allChemical.append(Chemical(line, sourceType=sourceType))

for chemical in allChemical:
    print chemical.chemicalName #Prints all chemicals and their data in list format

for chemical in allChemical(["o2"]):
    print chemical.chemicalName

输出以下错误,我试图弥补没有运气; TypeError:“list”对象不可调用


Tags: theinechoselfnoneobjectdeftv
3条回答

尝试此功能:

def chemByString(chemName,chemicals,priority="echo"):
    for chemical in chemicals:
        chemDict = chemical.toDict(priority)
        if chemDict["chemicalName"] == chemName
            return chemical
    return None

此函数使用toDict()类中的Chemical方法。从Chemical类粘贴的代码解释了此方法从化学对象返回字典:

def toDict(self, priority="echo"):
    """Returns a dictionary of all the variables, in the form {"mass":<>, "charge":<>, ...}.
    Design used is to be passed into the Echo and TV style line format statements."""
    if priority in ["echo", "tv"]:
    # Creating the dictionary by a large, to avoid repeated text
        return dict([(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))
            for attributeName in ["chemicalName", "mass", "charge"]])
    else:
        raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print

这本词典是这样的:

"chemicalName" : <the chemical name>
"mass" :         <the mass>
"charge" :       <the charge>

我在上面创建的函数所做的是遍历列表中的所有化学品,找到第一个名称等于“o2”的化学品,并返回该化学品。使用方法如下:

chemByString("o2",allChemicals).chemicalName

如果上述方法不起作用,可能需要尝试使用替代优先级(“tv”),但我不确定这是否会产生任何影响:

chemByString("o2",allChemicals,"tv").chemicalName

如果没有找到化学物质,函数返回None

chemByString("myPretendChemical",allChemicals).chemicalName

编辑:查看我的新答案。把这个留在这里,因为它可能仍然是有用的信息。你知道吗

在python中,list对象是一个包含其他对象的结构,它包含的每个对象都有一个索引。像这样:

Index    Object
0        "hello"
1        "world"
2        "spam"

如果要访问其中一个对象,必须知道其索引:

objList[0] #returns "hello" string object

如果您不知道索引,可以使用index方法找到它:

objList.index("hello") #returns 0

然后可以使用找到的索引从列表中获取对象:

objList[objList.index("hello")]

但是这有点傻,因为你可以:

"hello"

在这种情况下会产生相同的结果。你知道吗

你的allChemical对象是一个列表。看起来行chemicalFiles = ("/home/temp.txt")正在用某种类型的对象填充您的列表。为了回答您的问题,您必须提供有关列表中包含的对象的更多信息。我假设信息在您正在使用的ParseClasses模块中。你知道吗

如果您可以提供有关正在导入的Chemical对象的更多信息,这可能会大大有助于解决您的问题。你知道吗

如果列表中包含的对象是来自str的子类,则这可能起作用:

allChemical[allChemical.index("o2")].chemicalName

"02"str对象,因此index将在列表中查找str对象(或str的子类对象)以查找其索引。但是,如果对象不是字符串,它将找不到它。你知道吗

作为学习练习,请尝试以下方法:

class Chemical(str):
'''A class which is a subclass of string but has additional attributes such as chemicalName'''
    def __init__(self,chemicalName):
        self.chemicalName = chemicalName

someChemicals = [Chemical('o2'),Chemical('n2'),Chemical('h2')]

for chemical in someChemicals: print(chemical.chemicalName) 
#prints all the chemical names
print(someChemicals[0].chemicalName) 
#prints "o2"; notice you have to know the index ahead of time
print(someChemicals[someChemicals.index("o2")].chemicalName) 
#prints "o2" again; this time index found it for you, but
#you already knew the object ahead of time anyway, sot it's a little silly

这是因为索引能够找到您要查找的内容。如果它不是一个字符串,它就找不到它,如果你不知道“o2”是什么索引,如果你想得到你的化学品列表中的一种特定的化学品,你就必须了解更多关于这些物体的信息。你知道吗

问题是这两条线

for chemical in allChemical(["o2"]):
    print chemical.chemicalName

allChemical是一个列表,你不能只做a_list()。看起来您正在试图在列表中找到['o2']或只是'o2'。为此,您可以获取该项的索引,然后从列表中获取该索引。你知道吗

allChemical[allChemical.index("o2")]

相关问题 更多 >

    热门问题