Python程序中关于类的AttributeError
我正在做Python书中的一个练习,包括创建一个类和一个子类。当我尝试运行该程序时,我遇到以下错误:Python程序中关于类的AttributeError,python,class,subclass,attributeerror,Python,Class,Subclass,Attributeerror,我正在做Python书中的一个练习,包括创建一个类和一个子类。当我尝试运行该程序时,我遇到以下错误:AttributeError:“Customer”对象没有属性“name”,当它尝试遍历这段代码时:self.name.append(name) 由于这是我第一次在Python中处理类和对象,我确信我在某些地方犯了一些明显的错误,但我似乎无法理解。我已经看过了创建类和编写成员函数的文档,它看起来是正确的,但显然不是。我希望Customer子类从Person超类继承name、address和phon
AttributeError:“Customer”对象没有属性“name”
,当它尝试遍历这段代码时:self.name.append(name)
由于这是我第一次在Python中处理类和对象,我确信我在某些地方犯了一些明显的错误,但我似乎无法理解。我已经看过了创建类和编写成员函数的文档,它看起来是正确的,但显然不是。我希望Customer子类从Person超类继承name、address和phone属性,但它似乎没有这样做
这是我的密码:
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()
您的子类客户正在重新定义
\uuu init\uu
方法,而不调用超类方法。这意味着您在Person.\uuuu init\uuu
中创建姓名、地址和电话属性的行永远不会执行
您希望您的Customer.\uuuuu init\uuu
方法在某个时候调用Person.\uuuuu init\uu
。使用Pythonsuper()
super(Customer,self)。\uuuu init\uuuu()
如@Pedro Wemeck所说
但是有一个问题需要注意:如果您使用的是python2.x
,请使用以下两种方式之一进行更改:
class Person -> class Person(object)
或
super
只能在新型类中使用def changeOnMailingList():
if onMailingList == False:
onMailingList == True
else:
onMailingList == False
您应更改为:
def changeOnMailingList(self):
if self.onMailingList == False:
self.onMailingList == True
else:
self.onMailingList == False
AttributeError:“非类型”对象没有属性“附加”
,因为self.name
是无的,并且不能使用属于列表
对象的append
您可以直接使用
self.name=name
。修复了以前的错误,但现在我得到了一个新错误:AttributeError:'NoneType'对象没有属性“append”
,环顾四周,这是因为append()返回None。有没有一种更优雅的方法可以不用append编写成员函数?谢谢。我在changeOnMailingList()
函数中发现了错误,但我没有意识到这里不能使用append。我刚刚按照你的建议使用了self.name=name
,现在运行良好。
def changeOnMailingList():
if onMailingList == False:
onMailingList == True
else:
onMailingList == False
def changeOnMailingList(self):
if self.onMailingList == False:
self.onMailingList == True
else:
self.onMailingList == False