【发布时间】:2020-11-02 14:26:39
【问题描述】:
我定义了一个名为 Email 的新类,并且必须创建一些方法。问题是,我在构造函数中定义了变量,Spyder上的代码分析一直说inbox、is_spam和has_been_read在我的一些方法中没有定义,即使我在构造函数中定义了它.
我到处搜索,但我真的不知道我做错了什么?
我正在使用 Spyder 4.1.5 和 Python 3.8
我的代码如下:
class Email(object):
def __init__(self, has_been_read, email_contents, is_spam, from_address, inbox):
assert type(has_been_read) == bool and type(is_spam) == bool
self.has_been_read = has_been_read
self.email_contents = email_contents
self.is_spam = is_spam
self.from_address = from_address
self.__inbox = []
def mark_as_read(self):
# Creating method to change has_been_read boolean to True
return self.has_been_read == True
def mark_as_spam(self):
# Creating method to change is_spam to True
return self.is_spam == True
def add_email(self, eamil_contents, from_address):
return Email(False, email_contents, False, from_address)
inbox.append(Email)
def get_count(self):
print(len.inbox)
def get_email(self, i):
print(inbox[i].email_contents)
return inbox[i].mark_as_read
def get_unread_emails(self):
for i in inbox:
if has_been_read == False:
print(i)
def get_spam_emails(self):
for i in inbox:
if is_spam == True:
print(i)
def delete(self, i):
del self.inbox[i]
【问题讨论】:
-
您忘记使用
self访问它们。self.__inbox、self.is_spam等 -
一个问题是你不应该在返回语句中使用两个“=”符号:
return self.has_been_read == True -
附带说明,您确定要使用name mangling 并使用以
__inbox开头的双下划线名称吗? -
@go2nirvana 谢谢,成功了!我不知道我是怎么错过的
-
@ThierryLathuille 我什至没有意识到这一点,所以感谢您的提醒,我删除了两个下划线