关于类的Python程序中的AttributeError

2024-10-03 11:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python书中做了一个练习,涉及创建一个类和一个子类。当我试图运行这个程序时,我得到了以下错误:AttributeError: 'Customer' object has no attribute 'name',当它试图遍历这段代码时:self.name.append(name)

由于这是我第一次在Python中处理类和对象,我肯定我在某些地方犯了一些明显的错误,但我似乎无法理解。很明显,创建成员函数是不正确的。我希望Customer子类从Person超类继承name、address和telephone属性,但它似乎没有这样做?在

这是我的代码:

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()

Tags: nameselfnonefalseaddressdefcustomer子类
2条回答
  1. 使用super(Customer, self).__init__()如@Pedro Wemeck所说

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

    class Person -> class Person(object)
    

    或者

    ^{pr2}$

    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是None,并且不能使用属于list对象的append

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

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

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

class Customer(Person):

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

相关问题 更多 >