python - 从子类调用时出现 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'
如果他们选择加入邮件列表,程序应该显示姓名、地址、电话号码、客户号码和一条消息。我的输出是姓名、地址和电话号码(都来自超类),但不是客户号码和邮件列表消息(来自子类)。
解决方案
在您的Customer
初始化中,您可能希望使用super
而不是显式使用Person
类。此外,在同一个 init 中,您将self.set_custnum
和都self.set_mail
用作变量,并将其定义为方法。尝试使用我编辑的Customer
init。
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)
推荐阅读
- javascript - 如何使用 jest 测试以下给定的功能?
- google-api - 通过 Google Drive api v3 上传的文件是在用户驱动器而不是 shard 驱动器上创建的
- c++ - 在结构中设置数组元素时出现总线错误
- javascript - 如何访问我从客户端(NodeJs)发布的数据
- class - 类和对象的通用术语是什么?
- javascript - 如何在 Firestore 中增加一个数字?
- regex - Powershell如何使用Regex替换word文档中的标签
- spring-boot - 使用 Spring Boot 在 Spring Security 中加载具有相同前缀的属性
- node.js - 使用 express 服务器从另一个站点下载文件会生成完整的 html 源代码而不是实际文件
- python - pandas.DataFrame.hist() 占用大量内存和执行时间