Python脚本错误“函数对象没有属性'firstName'

时间:2016-03-24 18:11:47

标签: python python-3.x

我正在尝试制作一些自己的脚本来练习我正在学习的东西。但是我在下面的脚本中遇到了一些问题。

#!/usr/bin/python
def empInfoEntry():
    firstName = input("Enter Employee's First Name: ")
    lastName = input("Enter Employee's Last Name: ")
    address = input("Enter Employee's Address: ")
    city = input("Enter Employee's City: ")
    state = input("Enter Employee's Complete State: ")
    zip = input("Enter Employee's Zip Code: ")

def empInfo():
    empFirstName = empInfoEntry.firstName
    empLastName = empInfoEntry.lastName
    print (empFirstName + " " + empLastName)
    empAddress = empInfoEntry.address
    print (empAddress)
    empCity = empInfoEntry.city
    empState = empInfoEntry.state
    empZip = empInfoEntry.zip
    print (empCity + ", " + empState + " " + empZip)


empInfoEntry()
empInfo()

根据错误“未处理的AttributeError”函数; object没有属性'firstName'“

我查了一下,但我发现的大部分结果都非常复杂,而且很难解决我的问题。

我知道当这个脚本运行时,它以empInfoEntry()

开头

它可以工作,因为我可以输入所有信息。

然而,empInfo()似乎给了我那个功能错误。我也试过使用一个简单的print (firstName),虽然我知道它在函数之外。即使我将其附加到打印(empInfoEntry.firstName),它也会给我一个错误。

我可以想象这是因为没有回报,但我仍然对回报感到有点困惑,就像人们所说的一样简单。

任何eli5回复都会受到赞赏,但完整的解释也会有效。

感谢。

在Windows 8上也使用python 3.4和eric 6

2 个答案:

答案 0 :(得分:1)

首先,尝试使用raw_input()代替input()。 根据{{​​3}},input()实际上是eval(raw_input())。你可能想知道什么是eval(),查看文档,我们不在这里讨论。抱歉我认为它是Python 2。

由于您似乎离开始学习Python不远,我不会为您编写课程。只需使用函数和基本数据结构。

如果您有兴趣,请查看official documentation以了解Python中的命名约定。

#!/usr/bin/python

def enter_employee_info_and_print():
    # use a dictionary to store the information
    employee_info = {}

    employee_info['first_name'] = input("Enter Employee's First Name: ")
    employee_info['last_name'] = input("Enter Employee's Last Name: ")
    employee_info['address'] = input("Enter Employee's Address: ")
    employee_info['city'] = input("Enter Employee's City: ")
    employee_info['state'] = input("Enter Employee's Complete State: ")
    employee_info['zip'] = input("Enter Employee's Zip Code: ")

    first_name = employee_info['first_name']
    last_name = employee_info['last_name']
    # pay attention that there is no space between `print` and `(`
    print(first_name + " " + last_name)
    address = employee_info['address']
    print(address)
    city = employee_info['city']
    state = employee_info['state']
    zip = employee_info['zip']
    print(city + ", " + state + " " + zip)

# use this statement to run a main function when you are directly running the script.
if __name__ == '__main__':
    enter_employee_info_and_print()

答案 1 :(得分:0)

试试这个。我认为这是你要找的东西。

class InfoEntry(object):
  def __init__(self):
    self.first_name = input("Enter your first name:")
    self.last_name = input("Enter your last name:")

  def __str__(self):
    return self.first_name + " " + self.last_name

me = InfoEntry()
print(me)

虽然函数 can 具有属性,但当您想要某些东西来保存信息时,您知道的格式是先验的,您想要的是class