我的python类在那里有明确的那个时返回No Attribute

时间:2017-01-07 15:42:15

标签: python class

以下是代码,解释位于底部

#classing tests

class Employee(object):
    raise_amount = 1.04
    def __init__(self, name, age, pay):
        self.name = name
        self.age = age
        self.pay = pay

    def __repr__(self):
        return ("Employee: {} Age: {} Pay: {:.2f}/month".format(self.name, self.age, self.pay))

    def __str__(self):
        return ("{} is {} and gets {:,.2f} per month".format(self.name, self.age, self.pay))

    @property
    def show_pay(self):
        print ("{0} gets {1:,.2f} per month".format(self.name, self.pay))

    @property
    def pay_rise(self):
        self.pay *= self.raise_amount


class Head(Employee):
    raise_amount = 1.1
    def __init__(self, name, age, pay, employees=None):
        super().__init__(name, age, pay)
        if self.employees == None:
            self.employees = []

        else:
            self.employees = employees


    def add_employee(self, employe):
        if employe not in employees:
            self.employees.append(employe)


    def remove_employee(self, employe):
        if employe in employees:
            self.employees.remove(employe)

    @property
    def show_employees(self):
        for i in self.employees:
            print(i.name())

employee_1 = Employee("John", 55, 21377)
head1 = Head("Bob", 21, 22336)

employee_1.show_pay
employee_1.pay_rise
employee_1.show_pay

head1.show_pay
head1.pay_rise
head1.show_pay

print(head1)
print(repr(head1))

所以这是我的代码,当我运行它时,它返回AttributeError: type object 'Head' has no attribute 'employees。请帮忙,我很困惑。请帮助,因为它一直有效,直到我添加了头类与输入员工,这是令人沮丧的

2 个答案:

答案 0 :(得分:1)

问题出现在if self.employees is None:构造函数的行__init__()中。 正如例外所述,employees中没有名为self的属性,因为您尚未定义它,因此错误。

要检查是否存在属性,您应该使用hasattr,以便上面的行变为if not hasattr(self, 'employees'):。 通过此更改,代码可以正常运行

通常认为重构pythonic是以不需要使用hasattr或类似检查的方式重构代码。

答案 1 :(得分:0)

在课程Head中,您可以在为其分配值之前访问属性self.employees,因此AttributeErroremployees。你可能意味着class Head(Employee): raise_amount = 1.1 def __init__(self, name, age, pay, employees=None): super().init(name, age, pay) self.employees = [] if employees == None else employees ,参数:

$.ajax({
    url:"url",
    dataType: "text",
    cache: false,
    success: function(data){
        window.open('url','_self');
   }
});