当酒店访客未添加有效的电子邮件地址时,我想引发TypeError

时间:2018-11-12 02:20:17

标签: python

当酒店访客未添加有效的电子邮件地址,但我却收到此错误时,我想引发TypeError:

  

回溯(最近通话最近):文件   “ /Users/Bex/PycharmProjects/Programmes/OOP/Hotel.py”,第43行,在          jane = Hotel.from_string(“ Jane,Doe,janedoe @ gmail.com”)文件   “ /Users/Bex/PycharmProjects/Programmes/OOP/Hotel.py”,第15行,在   from_string       返回cls(名字,姓氏,电子邮件)文件“ /Users/Bex/PycharmProjects/Programmes/OOP/Hotel.py”,第25行,在   初始化       引发TypeError(“您输入了无效的电子邮件地址。”)TypeError:您输入了无效的电子邮件地址。

class Hotel:
    visitors = 0
    rooms = ['single', 'double', 'queen', 'king', 'executive']

    @classmethod
    def display_no_of_visitors(cls):
        if Hotel.visitors > 0:
            return "There are currently {} visitor(s)".format(Hotel.visitors)
        else:
            return "There are no visitors currently at the hotel"
    enter code here
    @classmethod
    def from_string(cls, str):
        first_name, last_name, email = str.split(",")
        return cls(first_name, last_name, email)


    def __init__(self, first_name, last_name, email):
        self.first_name = first_name
        self.last_name = last_name
        for char in email:
            if char in "@":
                self.email = email
            else:
                raise TypeError("You've entered an invalid email address.")
        Hotel.visitors += 1

    @property
    def email(self):
        return self.email

    def __repr__(self):
        return "Full Name: {} {}\n Email Address: {}".format(self.first_name, self.last_name, self.email)

    def full_name(self):
        return "{} {}".format(self.first_name, self.last_name)

    def checkout(self):
        Hotel.visitors -= 1
        return "{} {} has checked out".format(self.first_name, self.last_name)


jane = Hotel.from_string("Jane,Doe,janedoe@gmail.com")

print(jane.first_name)
print(jane.last_name)`enter code here`
print(jane.display_no_of_visitors())
print(jane.email)

1 个答案:

答案 0 :(得分:0)

欢迎您,Alex!

在您的__init__中,它正在提升您的TypeError,因为它使用循环来检查每个字符是否为@,并且由于并非每个字符都会失败。相反,您可以放下循环并像这样检查它:

def __init__(self, first_name, last_name, email):
    self.first_name = first_name
    self.last_name = last_name

    if "@" in email:
        self.email = email
    else:
        raise TypeError("You've entered an invalid email address.")
    Hotel.visitors += 1

这似乎现在没有错误。 您还需要删除一些额外的代码,以避免在第11和46行出现语法错误。(enter code here