关于类的Python程序中的AttributeError

时间:2014-06-05 02:33:43

标签: python class subclass attributeerror

我正在做一本涉及创建类和子类的Python书籍。当我尝试运行程序时遇到以下错误:AttributeError: 'Customer' object has no attribute 'name',当它试图通过这段代码时:self.name.append(name)

由于这是我第一次使用Python处理类和对象,我确信我在某个地方犯了一些明显的错误,但我似乎无法弄明白。我查看了创建类和编写成员函数的文档,看起来是正确的,但显然不是。我希望Customer子类继承Person超类的名称,地址和电话属性,但它似乎没有这样做?

这是我的代码:

class Person:

    def __init__(self):
        self.name = None
        self.address = None
        self.telephone = None

    def changeName(self, name):
        self.name.append(name)

    def changeAddress(self, address):
        self.address.append(address)

    def changeTelephone(self, telephone):
        self.telephone.append(telephone)

class Customer(Person):

    def __init__(self):
        self.customerNumber = None
        self.onMailingList = False

    def changeCustomerNumber(self, customerNumber):
        self.customerNumber.append(customerNumber)

    def changeOnMailingList():
        if onMailingList == False:
            onMailingList == True
        else:
            onMailingList == False

def main():

    customer1 = Customer()

    name = 'Bob Smith'
    address = '123 Somewhere Road'
    telephone = '111 222 3333'
    customerNumber = '12345'

    customer1.changeName(name)
    customer1.changeAddress(address)
    customer1.changeTelephone(telephone)
    customer1.changeCustomerNumber(customerNumber)

    print("Customer name: " + customer1.name)
    print("Customer address: " + customer1.address)
    print("Customer telephone number: " + customer1.telephone)
    print("Customer number: " + customer1.customerNumber)
    print("On mailing list: " + customer1.OnMailingList)

    customer1.changeOnMailingList()

    print("On mailing list: " + customer1.OnMailingList)

main()

2 个答案:

答案 0 :(得分:1)

您的子类Customer正在重新定义__init__方法而不调用超类方法。这意味着永远不会执行创建名称,地址和电话属性的Person.__init__中的行。

您希望Customer.__init__方法在某个时刻调用Person.__init__。使用Python super()

class Customer(Person):

    def __init__(self):
        super(Customer, self).__init__()
        self.customerNumber = None
        self.onMailingList = False

答案 1 :(得分:1)

  1. 使用super(Customer, self).__init__()作为@Pedro Wemeck说

    但是有一个问题需要注意:如果您使用python 2.x,请更改为以下两种方式之一:

    class Person -> class Person(object)
    

    class Customer(Person):
        def __init__(self):
            Person.__init__(self)
    

    super只能用于新式的课程

  2. 有一个问题:

    def changeOnMailingList():
        if onMailingList == False:
            onMailingList == True
        else:
            onMailingList == False
    

    你应该改为:

    def changeOnMailingList(self):
        if self.onMailingList == False:
            self.onMailingList == True
        else:
            self.onMailingList == False
    
  3. 您获得AttributeError: 'NoneType' object has no attribute 'append',因为self.name为无,并且无法使用属于append对象的list

    < / LI>

    您可以直接使用self.name = name