当我从子类中调用任一方法(get .__ custnum或get__mail)时,我收到一个属性错误,提示该对象没有名为Subclass__attribute的属性。
我检查了不仅仅是get_custnum不能正常工作,还是get_mail出现了问题。
class Customer(Person):
def __init__(self, name, address, telnum, custnum, mail):
Person.__init__(self, name, address, telnum)
self.set_custnum = custnum
self.set_mail = mail
def set_custnum(self, custnum):
self.__custnum = custnum
def set_mail(self, mail):
self.__mail = mail
if mail == True:
self.__mail = ('You have been added to the mailing list.')
def get_custnum(self):
return self.__custnum
def get_mail(self):
return self.__mail
from Ch11 import Ch11Ex3Classes
...
customer = Ch11Ex3Classes.Customer(name, address, telnum, custnum, mail)
...
print ('Customer Name: ', customer.get_name())
print ('Customer Address: ', customer.get_address())
print ('Customer telephone number: ', customer.get_telnum())
print ('Customer Number: ', customer.get_custnum())
print (customer.get_mail())
return self.__custnum
AttributeError: 'Customer' object has no attribute '_Customer__custnum'
如果程序选择加入邮件列表,则程序应显示姓名,地址,电话号码,客户号码和一条消息。我的输出是姓名,地址和电话号码(均来自超类),而不是客户号码和邮件列表消息(均来自子类)。
答案 0 :(得分:1)
在您的Customer
初始化中,您可能想使用super
而不是显式使用Person
类。另外,在同一初始化中,您同时使用了self.set_custnum
和self.set_mail
作为变量,并将其定义为方法。尝试使用我编辑过的Customer
初始化。
class Customer(Person):
def __init__(self, name, address, telnum, custnum, mail):
super().__init__(self, name, address, telnum)
self.set_custnum(custnum)
self.set_mail(mail)
答案 1 :(得分:0)
self.set_custnum = custnum
未调用该方法。您需要在__init__
中调用该方法:
class Customer(Person):
def __init__(self, name, address, telnum, custnum, mail):
Person.__init__(self, name, address, telnum)
self.set_custnum(custnum)
self.set_mail(mail)