因为我是python编程语言和OOP概念的新手。 我正在锻炼班级和目标代码。虽然我收到了这个错误
AttributeError:类型对象'Employee'没有属性'empCount'“
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount = Employee.empCount + 1
def DisplayCount(self):
print("Total Employee %d" % Employee.empcount)
def DisplayEmployee(self):
print("Name:",self.name," Salary:",self.salary)
码
emp1 = Employee("Zara", 1000)
emp2 = Employee("Brad", 1500)
emp1.DisplayEmployee()
emp2.DisplayEmployee()
print("Total Employee %d" % Employee.empCount)`emp1 = Employee("Zara", 1000)
emp2 = Employee("Brad", 1500)
emp1.DisplayEmployee()
emp2.DisplayEmployee()
print("Total Employee %d" % Employee.empCount)`
谁能告诉我这里有什么问题?解释。
答案 0 :(得分:3)
问题是Employee.empCount
尚未在班级定义,而您正试图访问它。如果您的目的是根据创建的实例计算一个tap员工数,那么像这样的类变量就可以了。但是,通常不建议以这种方式跨实例共享变量,而是建议找到可靠的替代方案。
注意类Employee继承自object,这在Python中称为新样式类。
In [29]:
class Employee(object):
empCount = 0
def __new__(cls, *args, **kwargs):
cls.empCount += 1
return super(Employee, cls).__new__(cls, *args, **kwargs)
def __init__(self, name, salary):
self.name = name
self.salary = salary
def DisplayCount(self):
print("Total Employee %d" % Employee.empcount)
def DisplayEmployee(self):
print("Name:",self.name," Salary:",self.salary)
## -- End pasted text --
In [30]: emp1 = Employee("Zara", 1000);emp2 = Employee("Brad", 1500)
In [31]: emp1.empCount
Out[31]: 2
In [32]: emp3 = Employee("Tes", 100)
In [33]: emp1.empCount
Out[33]: 3
答案 1 :(得分:3)
在__init__
中,您正在尝试访问不存在的类变量:
Employee.empCount = Employee.empCount + 1
# ^^^^^^^^^^^^^^^^^ what's the initial value?
您需要在类级别定义变量,以便对变量进行后续更新,并且python区分大小写,因此您需要修复DisplayCount
中的下一个错误:
class Employee:
empCount = 0
...
def DisplayCount(self):
print("Total Employee %d" % Employee.empCount)
# ^^^^^
答案 2 :(得分:0)
您需要设置'Employee.empCount'变量。
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount = 0
Employee.empCount = Employee.empCount + 1
这应该有效。
答案 3 :(得分:0)
您的问题是您正在尝试计算员工班级中的员工人数。这就像每个员工都知道总数...
每次创建员工时,您必须拥有一种可以计算员工数量的类,或者最简单的方法是将员工存储在列表中,然后查看列表的大小。
解决方案可能是:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def DisplayEmployee(self):
print("Name:",self.name," Salary:",self.salary)
代码:
employees = []
employees.append(Employee("Zara", 1000))
employees.append(Employee("Brad", 1500))
[e.DisplayEmployee() for e in employees]
print("Total Employee %d" % len(employees))
导致:
Name: Zara Salary: 1000
Name: Brad Salary: 1500
Total Employee 2
希望能够帮助你。