我在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()
使用
super(Customer, self).__init__()
如@Pedro Wemeck所说但有一个问题需要注意:如果使用
python 2.x
,请按以下两种方式之一进行更改:或者
^{pr2}$super
只能在新样式类中使用有一个问题:
您应该更改为:
得到
AttributeError: 'NoneType' object has no attribute 'append'
,因为self.name
是None,并且不能使用属于list
对象的append
。您可以直接使用
self.name = name
。在您的子类Customer正在重新定义
__init__
方法,而不调用超类方法。这意味着,Person.__init__
中创建名称、地址和电话属性的行永远不会执行。在您希望您的
Customer.__init__
方法在某个时刻调用Person.__init__
。使用Pythonsuper()
。在相关问题 更多 >
编程相关推荐