如何将raw_input用于定义

时间:2018-03-14 05:33:27

标签: python function class python-2.x raw-input

问题

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

但是,我不确定如何让班级使用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)

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

  

追踪(最近一次呼叫最后一次):

     

文件" C:/Users/NAME/Desktop/PTable.py",第146行,

hub()
     

文件" C:/Users/NAME/Desktop/PTable.py" ;,第143行,在中心

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

属性错误:' str'对象没有属性' name'

问题

你知道我是如何做到这一点所以用户能够输入元素的名称(原子符号)并且代码打印出信息吗?

1 个答案:

答案 0 :(得分:2)

恢复元素

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

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

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__

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

class PTable(object):

    ...

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