我试图学习python类,我试图了解类变量的工作原理。当我执行下面的代码时,我看到了这个错误。我只是想了解为什么python抱怨名字"员工"。当我将语句移到Employee.employeecount = Employee.employeecount + 1
__init__
方法内时,我看到它没有抱怨。有人可以帮我理解究竟发生了什么。
非工作代码:
class Employee(object):
employeecount = 0
Employee.employeecount = Employee.employeecount + 1
def __init__(self,name,salary):
self.name = name
self.salary = salary
def getdata(self):
self.salary += 1
print "Employee name: %s \nEmployee Salary: %d" % (self.name,self.salary)
def getname(self):
return self.name
def getsalary(self):
return self.salary
emp1 = Employee('Pradeep',8000)
emp1.getdata()
emp2 = Employee('Maddy',9000)
emp2.getdata()
print "Employee Count is %d" % Employee.employeecount
print "Employee Count is %d" % Employee.employeecount
name = emp1.getname()
salary = emp1.getsalary()
print "Name is %s and salary is %d" % (name,salary)
python classes.py
Traceback (most recent call last):
File "classes.py", line 4, in <module>
class Employee(object):
File "classes.py", line 6, in Employee
Employee.employeecount = Employee.employeecount + 1
NameError: name 'Employee' is not defined
答案 0 :(得分:1)
问题是您在类定义中使用了Employee.employeecount = Employee.employeecount + 1
行;这将在您的程序启动的那一刻开始执行,而不是在创建新的Employee
时执行。
在那个时间点,Employee
课程将会看到Employee.employeecount
,并尝试寻找一些已经制作的Employee
课程 - 它不会意识到你想要它指自己。在那个时间点,Employee
尚未正确定义,因为您正在定义它。另一方面,如果将它放在__init__
函数中,您会发现没有问题 - 因为当您实际创建Employee
时,该类已被正确定义。
那时你要做的只是employeecount = employeecount + 1
。这将摆脱错误,但这可能不是你想要做的。如果您想在每次创建新员工时添加计数,请将Employee.employeecount = Employee.employeecount + 1
行添加到__init__
函数中。这应该可以解决问题。
答案 1 :(得分:0)
您希望更改代码,以便在init
中增加计数器,以便每次实例化Employee
时,计数器都会增加。
class Employee(object):
employeecount = 0 # Start of program this is set to 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.employeecount += 1 # Add 1 each time you create an Employee
您没有在employeecount
下方Employee
引用employeecount = 0
,因为您已经在班级。
class Employee(object):
# This is at class level - you don't use "ClassName.variableName"
# You just use "variableName"
这就是employeecount = 0
没有给你错误而Employee.employeecount = Employee.employeecount + 1
没有错误的原因。
您的代码在init
中工作,因为您必须在变量名之前使用类名来访问类变量。
def __init__(self,name,salary):
# This is at the instance level
# To access a class variable you have to put the class name first
答案 2 :(得分:0)
当您将Employee.employeecount = Employee.employeecount + 1
移动到__init__
时,您每次向新对象发送内容时都会增加此employeecount变量。创建对象时会调用类的__init__
方法,这就是错误消失的原因。