这是来自网络的简单python 3目标代码,它不依赖于平台。我无法工作 班级员工:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print (Employee.fullname(emp_1))
print (emp_2.fullname())
The error I get is as follows:
NameError Traceback(最近一次调用最后一次) in() ----> 1级员工: 2 3 def init (自我,第一,最后,付费): 4 self.first = first 5 self.last = last
员工()中的10返回'{} {}'。format(self.first,self.last) 11 ---> 12 emp_1 =员工('John','Doe','80000') 13 emp_2 =员工('Jane','Foo','90000') 14
NameError:名称'Employee'未定义
答案 0 :(得分:3)
缩进在Python中至关重要。请尝试以下代码。
您的类实例必须在外部定义类本身。对于emp_1
和emp_2
的定义没有缩进,可以认识到这一点。
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print(Employee.fullname(emp_1))
print(emp_2.fullname())
答案 1 :(得分:0)
这只是一个缩进错误。
Python通过缩进定义了classes
,methods
和其他块的范围。通常使用4个空格。
由于您将emp_1
和emp_2
的实例化与类的方法具有相同的缩进,因此它们实际上是该类的一部分。
你可能意味着:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print (Employee.fullname(emp_1))
print (emp_2.fullname())
答案 2 :(得分:0)
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{}{}'.format(self.first, self.last)
def main():
emp_1 = Employee('John','Doe','80000')
emp_2 = Employee('Jane','Foo','90000')
emp_2.fullname()
print (Employee.fullname(emp_1))
print (emp_2.fullname())
if __name__ == '__main__':
main()