python中的错误异常处理

2024-09-28 01:32:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

class personData ():
    def __init__(self, age, spouse = None, children = 0):
        self.age = age
        self.children = children
        self.spouse = spouse
        if self.spouse == None:
            del self.spouse
            print "A %s year old person" % str(self.age)    


    def marries(self, name):
        if self.spouse == None:
            self.spouse = name
        else:
            try:
                self.marries(name)
            except Exception as detail:
                print "spouse exists:", self.spouse

    def divorces(self):
       if self.spouse == None:
            raise AttributeError,  " Not married, divorce impossible"

我想做的是:

def divorces(self):
 if self.spouse != None:    ##   thats mean the person has a spouse,
   self.spouse = None       ##    I think that should remove the spouse, right?

如果我们再次要求离婚,这应该是一个例外,因为配偶被除名了。你知道吗

假设我的:

person = personData(30, 'Sue')

person.spouse应该是Sue,如果我调用person.marries('Anna')会引发异常,现在如果我调用person.divorce()会删除配偶('Sue')。当我打电话给person.divorce()的时候,我会遇到一个例外,说“没有配偶”,如果我做不到这一点,任何帮助都将不胜感激。你知道吗


Tags: nameselfnoneageifdefpersonprint
2条回答

您没有直接引发异常,如果引发异常是所需的结果,那么这是适当的。(或者,您可以只打印一条消息,而不处理任何异常。)您不需要在这里使用try-except。相反,只需提出异常,如:

if self.spouse == None:
    raise Exception( 'Divorce called but no spouse' )

而且,您永远也无法访问当前的try部分,因为hasattr(self, 'spouse')总是正确的。另一件事是,婚姻异常的发生是因为marries的无限递归调用,而不是因为直接引发异常。您不应该从marries内部调用marries。你知道吗

def divorces(self):
    if hasattr(self, 'spouse'):
        self.spouse = None

这将始终返回Truespouse属性可能被设置为None,但它仍然被设置。所以打印错误的else分支将永远不会到达。你知道吗

所以,你需要把它改成:

    if self.spouse == None:
        raise Exception('Not married')

__init__函数中,您正在执行:

    if self.spouse == None:
        del self.spouse

我只想跳过这个,将self.spouse设置为None;这样就不需要getattr()。你知道吗

示例

由于您似乎对完整的解决方案有些困惑,下面是整个课程:

class personData ():
    def __init__(self, age, spouse = None, children = 0):
        self.age = age
        self.children = children
        self.spouse = spouse

    def marries(self, name):
        # There is already a spouse, we don't do polygamy
        if self.spouse != None:
            raise AttributeError("Already married")

        # There is no spouse, so we can marry. You may kiss and a all that.
        self.spouse = name

    def divorces(self):
        # There is no spouse, so we can't divorce
        if self.spouse == None:
            raise AttributeError("Not married, divorce impossible")

        # We diverse, and reset the spouse
        self.spouse = None


person = personData(30, 'Sue')
person.divorces()
person.marries('Anna')
person.divorces()

# This gives an error
person.divorces()

额外小费

marries()函数中,您将执行以下操作:

try:
    marries(self,name)
except Exception as detail:
    print "spouse exists:", self.spouse

这是不正确的。这样做的目的是调用函数marries()(它不存在),将类实例selfname作为参数。你知道吗

你想做的是:

self.marries(name)

这将调用类实例self上的函数marries()self参数是由Python自动添加的,您不需要为简单的函数调用自己添加这个参数。你知道吗

此错误未被注意到,因为您正在捕获所有异常。这些“必须全部捕获”的pokemon异常几乎总是一个坏主意,因为您捕获的不仅仅是您预期的错误,还有所有没有预期的错误,例如编程错误。你知道吗

(我也不明白为什么在这里使用递归?)你知道吗

相关问题 更多 >

    热门问题