Using Class, Methods to define variables

2024/11/17 9:38:28

I have a number of chemicals with corresponding data held within a database, how do I go about returning a specific chemical, and its data, via its formula, eg 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 = tvself.echo = echodef __repr__(self):return str({"echo": self.echo, "tv": self.tv}) # Returns the respective stringsdef __getattribute__(self, item):"""Altered __getattribute__() function to return the alternative of .echo / .tv if the requestedattribute is None."""if item in ["echo", "tv"]:    if object.__getattribute__(self,"echo") is None: # Echo data not presentreturn object.__getattribute__(self,"tv") # Select TV dataelif object.__getattribute__(self,"tv") is None: # TV data not presentreturn object.__getattribute__(self,"echo") # Select Echo dataelse:return object.__getattribute__(self,item) # Return all dataelse:return object.__getattribute__(self,item) # Return all dataclass 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 objectsself.chemicalName.echo = chemicalNameself.mass.echo = massself.charge.echo = chargeelif sourceType.lower() == "tv": # Parsed chemical line for TV formatchemicalName          = inputLine.split(":")[0].strip()charge               = inputLine.split(":")[1].split(";")[0].strip()mass                 = inputLine.split(";")[1].split("&")[0].strip()# Store the objectsself.chemicalName.tv = chemicalNameself.charge.tv = chargeself.mass.tv  = molecularWeightelse: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 textreturn dict([(attributeName, self.__getattribute__(attributeName).__getattribute__(priority))for attributeName in ["chemicalName", "mass", "charge"]])else:raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise printfrom 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 formatfor chemical in allChemical(["o2"]):print chemical.chemicalName

outputs the following error which I have tried to remedy with no luck; TypeError: 'list' object is not callable

Answer

The issue is the two lines

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

allChemical is a list, and you can't just do a_list(). It looks like you're trying to find either ['o2'] or just 'o2' in a list. To do that, you can get the index of the item and then get that index from the list.

allChemical[allChemical.index("o2")]
https://en.xdnf.cn/q/118821.html

Related Q&A

Python Tkinter: Color changing grid of buttons?

I understand that you can make a button that can do some actions when clicked with Tkinter, but how can I just make a button that turns from one color to another when clicked? Then, from that, how do …

Writing a function that checks prime numbers

def primecheck(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False breakelse: return TrueIm trying to make a function that checks if an input is prime or not. This code does …

Getting error code 1 while installing geopandas with pip

This is the error I get when trying to install geopandas using pip install geopandas. Im using Python 3.7.Collecting geopandasUsing cached https://files.pythonhosted.org/packages/24/11/d77c157c16909bd7…

Find if a sorted array of floats contains numbers in a certain range efficiently

I have a sorted numpy array of floats, and I want to know whether this array contains number in a given range. Note that Im not interested in the positions of the number in the array. I only want to k…

Django Operation error: (2026, SSL connection error: SSL_CTX_set_tmp_dh failed)

I can not start my django server after running a statement through manage.py for generating class diagrams from db. And I always get this error but I dont know how to deal with it. OperationalError: (2…

TypeError with module object is not callable

I have a test folder the structure within the folder__init.py__ aa.py test.pyfor aa.pyclass aa:def __init__(self,max):self.max=maxprint max+1def hello(self):print(max)for test.pyimport aa abc = aa(100)…

How to access the GUI output?

Im developing one test bench which runs multiple tests via python gui and prints the output as below.A Passed B Passed C Passed D Passed E PassedButton from gui should be changed to Passed only when A,…

Is it possible to have an api call another api, having them both in same application?

I have a python application running on my localhost:3978. Is it possible to make an api call to http://localhost:3978/api/users from http://localhost:3978/api/accounts? @routes.get("/api/accounts…

Find word near other word, within N# of words

I need an enumerating regex function that identifies instances in a string when Word 1 is within N# words of Word 2 For example, here is my dataframe and objective: Pandas Dataframe Input data = [[ABC…

Create new files, dont overwrite existing files, in python

Im writing to a file in three functions and im trying not overwrite the file. I want every time i run the code i generate a new filewith open("atx.csv", w)as output:writer = csv.writer(output…