How do I call an attribute of a class instance using a variable as generated from input()
?
In the code the static print(E3.name)
works but if I try to replace 'E3' or 'melt' with variables it fails.
#User inputs element number and required attribute and Element() returns the value.
class Element():
def __init__(self, name, atomnum, atomwt, phase, melt, boil, crystal, category, shells, row, period):
self.name = name
self.atomnum = atomnum
self.atomwt =atomwt
self.phase = phase
self.melt = melt
self.boil = boil
self.crystal = crystal
self.category = category
self.shells = shells
self.row = row
self.period = period
E1 = Element("hydrogen", 1, 1.00794, "gas", -259, -253, "n/a", "non-metal", "1", 1, 1)
E2 = Element("helium", 2, 4.002602, "gas", -272, -269, "n/a", "nobel gas", "2", 1, 18)
E3 = Element("lithium", 3, 6.941, "solid", 181, 1342, "body-centred cubic", "alkali metal", "1,2", 2, 1)
E4 = Element("beryllium", 4, 9.012182, "solid",1287, 2469, "hexagonal", "alkaline earth metal", "2,2", 2, 2)
elnum = input("Element number eg. E3 ")
elattrib = input("Attribute of Element ")
print(E3.name, " melting point ", E3.melt, "ºC")
# This works and prints the correct value, but it´s static and I want dynamic inputs and results.
print(elnum.elattrib)
#This doesn't work - AttibuteError: 'str' Object has no attibute 'elattrib'