简体   繁体   English

在Python中实例化类时出现名称错误

[英]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: 好的,所以我尝试使用以下代码在Python中创建一个类,该类将参数分配给元素周期表的元素:

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? 我怀疑我错误地使用了__init__ ,如果是这样,该如何纠正错误? Thanks for reading. 谢谢阅读。

You are asking Python to pass in the values of two variables, named H and hydrogen , into the Element constructor: 您要让Python将名为Hhydrogen的两个变量的值传递到Element构造函数中:

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. 否则,您可以使用__init__ The traceback of the exception thrown would otherwise show that the method was actually invoked, and not point to the line calling Element() . 否则,对引发的异常的追溯将表明该方法实际上已被调用,而不是指向调用Element()的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM