Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an attribute through a variable [duplicate]

Basically I'm trying to make a little program using the periodic table library and I tried to make the first function which returns the mass of the given element.

def mass():
    Element = input("Element?   ")
    return periodictable.Element.mass

But this doesn't work because I'm trying to use a variable instead of an attribute so it says this:

Traceback (most recent call last):
File "<string>", line 424, in run_nodebug
File "<module1>", line 25, in <module>
File "<module1>", line 22, in main
File "<module1>", line 15, in mass
AttributeError: module 'periodictable' has no attribute 'Element'

The correct way to use the mass function with the periodic table should be this:

print(periodictable.H.mass)
print(periodictable.O.mass)
print(periodictable.Na.mass)

So what I'm asking is: can I give an attribute with a variable or do you have any other solution to make the user choose the element?

like image 607
Matteo Bianchi Avatar asked May 21 '26 13:05

Matteo Bianchi


2 Answers

The module seems to have a function for this:

periodictable.elements.symbol(Element).mass

This help page might be useful if you also need to access elements by name etc.:

help(periodictable.elements)

The general method for this sort of thing is using getattr:

getattr(periodictable, Element).mass

But this will also find other attributes of "periodictable", like the functions it defines and so on, so it's better to avoid it for this kind of application where you're looking up something typed by the user of your program.

like image 54
snowcat Avatar answered May 24 '26 01:05

snowcat


You can use getattr:

>>> import periodictable
>>> periodictable.Na.mass
22.98977
>>> element = 'Na'
>>> getattr(periodictable, element).mass
22.98977
like image 20
bla Avatar answered May 24 '26 03:05

bla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!