首页 > 解决方案 > 从子类调用时出现 AttributeError

问题描述

当我从子类调用任一方法(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

在我的 main 函数中的一个单独文件中。

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

运行 main 函数时出错。

return self.__custnum
AttributeError: 'Customer' object has no attribute '_Customer__custnum'

如果他们选择加入邮件列表,程序应该显示姓名、地址、电话号码、客户号码和一条消息。我的输出是姓名、地址和电话号码(都来自超类),但不是客户号码和邮件列表消息(来自子类)。

标签: python

解决方案


在您的Customer初始化中,您可能希望使用super而不是显式使用Person类。此外,在同一个 init 中,您将self.set_custnum和都self.set_mail用作变量,并将其定义为方法。尝试使用我编辑的Customerinit。

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)

推荐阅读