如何在定义中使用 raw_input 和 类

How do I use raw_input with classes in a definition

问题

我正在 Python 2.7 中编写脚本,让用户输入元素的原子符号。该脚本然后打印出有关该元素的信息。

但是,我不确定如何让 class 使用 raw_input 中的变量。这是为了提高可读性而删除了 118 个元素中的几个的代码:

代码

class PTable(object):
    def __init__(self, name, atom_num, atom_sym, atom_mass,period, group, atom_type,state):
        self.name = name
        self.atom_num = atom_num
        self.atom_sym = atom_sym
        self.atom_mass = atom_mass
        self.period = period
        self.group = group
        self.atom_type = atom_type
        self.state = state

h = PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas")
he = PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas")
li = PTable("Lithium",3,"Li",6.941,2,1,"Alkali metal","Solid")
be = PTable("Beryllium",4,"Be",9.0121831,2,2,"Alkaline earth","solid")
og = PTable("Oganesson",1,"H",1.008,1,1,"Nonmetal","Gas")

def results(name, num, sym, mass, per, gro, typ, state):
    print "Name:", name
    print "Atomic number:", num
    print "Atomic symbol:", sym
    print "Atomic mass:", mass
    print "Period:", per
    print "Group:", gro
    print "Type:", typ
    print "State:", state
# results(h.name, h.atom_num, h.atom_sym, h.atom_mass, h.period, h.group, h.atom_type, h.state)
def hub():
    x = raw_input("What element? ")
    results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)
    hub()

hub()

错误

给我语法错误的代码是:

results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)

错误很明显;语法错误,所以我尝试了另一种方式:

results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)

那也没有用,我得到了错误

Traceback (most recent call last):

File "C:/Users/NAME/Desktop/PTable.py", line 146, in

hub()

File "C:/Users/NAME/Desktop/PTable.py", line 143, in hub

results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)

AttributeError: 'str' object has no attribute 'name'

问题

你知道我怎么做才能让用户能够输入元素的名称(原子符号)并且代码打印出信息吗?

正在恢复元素

x = raw_input("What element? ") 为您提供了一个字符串,例如 'he',因此当您调用 x.name 时,您试图访问该字符串的属性而不是变量 he.

您应该做的是将元素存储在字典中,而不是将它们作为变量并使用用户提供的密钥访问它们。

periodic_table = {
    'h': PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas"),
    'he': PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas"),
    ...
}

symbol = raw_input("What element? ")

try:
    element = periodic_table[symbol]

except KeyError:
    print('This element does not exist')

打印元素

至于打印元素,我建议通过实施 PTable.__str__ 方法来实现更 object-oriented 的方法。

class PTable(object):

    ...

    def __str__(self):
        # Add in the format and information that you want to be printed
        return "Name: {}".format(self.name)

然后您可以直接打印您的元素。

print periodic_table['he']
# prints: 'Name: Helium'