nekomeido
nekomeido

Reputation: 37

Name Error when instantiating a class in Python

Okay, so I'm trying to create a class in Python that assigns parameters to the elements of the periodic table, using the following code:

class Element:
    def __init__(self, Symbol, Name, Number, Row, Column):
        self.Symbol = Symbol
        self.Name = Name
        self.Number = Number
        self.Row = Row
        self.Column = Column

However, when trying to create an instance of the class,

H = Element(H, hydrogen, 1, 1, 1)

I get the error message

NameError: name 'H' is not defined

I suspect I'm using __init__ incorrectly, and if so, how can the mistake be corrected? Thanks for reading.

Upvotes: 0

Views: 1560

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121962

You are asking Python to pass in the values of two variables, named H and hydrogen, into the Element constructor:

Element(H, hydrogen, 1, 1, 1)
#       ^  ^^^^^^^^

Those variables are not defined. Did you mean to pass in strings instead perhaps? If so, use string literal syntax (quotes):

H = Element('H', 'hydrogen', 1, 1, 1)

Your use of __init__ is otherwise fine. The traceback of the exception thrown would otherwise show that the method was actually invoked, and not point to the line calling Element().

Upvotes: 3

Related Questions