0

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'
ForceBru
  • 43,482
  • 10
  • 63
  • 98
Srete23
  • 13
  • 3
  • See [this](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) about accessing variables by name, See [`object.__getattribute__`](https://docs.python.org/3.9/reference/datamodel.html#object.__getattribute__) about accessing attributes dynamically – ForceBru Sep 03 '21 at 10:58

1 Answers1

0

This is a good question.

Python provides you a builtin function called getattr for getting attributes inside an object using a string. All you need to do is provide the object instance and the property name you're looking for. If that attribute does not exists, it raises an AttributeError, it's always important to keep that on mind if you're asking the user for the property name.

The code would look like this:

print(getattr(elnum, elattrib))
Dharman
  • 30,962
  • 25
  • 85
  • 135
TechNoHiru
  • 16
  • 1
  • Sorry, did not work for me. Still getting 'str' Object has no attibute 'elattrib'. Have found another solution that seems to work using def __repr__(self): return f"¨{name} .... – Srete23 Sep 03 '21 at 20:48
  • @Srete23 Oh yeah, my mistake, didn't see elnum isn't an Element instance. What you could do is add all the elements you have inside a list and ask the user for the element number with `int(input('Element number eg. 3 '))` and then get the element with the specified index from the list, and finally getting the `elattrib` from it. – TechNoHiru Sep 07 '21 at 12:35