Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的错误异常处理_Python_Python 2.7 - Fatal编程技术网

python中的错误异常处理

python中的错误异常处理,python,python-2.7,Python,Python 2.7,这是我的代码: 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

这是我的代码:

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"
我想做的是: 如果我们再次要求离婚,这应该是一个例外,因为配偶被除名了

让我们说我的:

person = personData(30, 'Sue')

person.party
将是
Sue
,如果我调用
person.marries('Anna')
将引发一个例外,现在如果我调用
person.discovery()
它将删除配偶(
'Sue'
)。我所坚持的是,当我打电话给person.discovery()时,它应该会引发一个例外,说“没有配偶存在”,而我无法做到这一点,任何帮助都将不胜感激。

你不是直接提出一个例外,如果提出一个例外是期望的结果,这是适当的。(或者,您可以只打印一条消息,不处理任何异常。)您无需使用
try
-
,除了此处的
。相反,只需引发异常,如:

if self.spouse == None:
    raise Exception( 'Divorce called but no spouse' )
此外,您永远无法访问当前的
try
部分,因为
hasattr(self,'配偶')
总是正确的。另一件事是,发生婚姻异常是因为对
marries
的无限递归调用,而不是因为直接引发异常。您不应该从
marries
内部调用
marries

def divorces(self):
    if hasattr(self, 'spouse'):
        self.spouse = None
这将始终返回
True
配偶
属性可以设置为
None
,但仍然设置。因此,永远不会到达打印错误的
else
分支

因此,您需要将其更改为:

    if self.spouse == None:
        raise Exception('Not married')
\uuuu init\uuuu
函数中,您正在执行以下操作:

    if self.spouse == None:
        del self.spouse
try:
    marries(self,name)
except Exception as detail:
    print "spouse exists:", self.spouse
我只想跳过这一步,将self.party设置为
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()
函数中,您正在执行以下操作:

    if self.spouse == None:
        del self.spouse
try:
    marries(self,name)
except Exception as detail:
    print "spouse exists:", self.spouse
这是不正确的。这样做的目的是调用函数
marries()
(该函数不存在),将类实例
self
name
作为参数

您想做的是:

self.marries(name)
这将调用类实例
self
上的函数
marries()
self
参数是由Python自动添加的,对于一个简单的函数调用,您不需要自己添加这个参数

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


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

person=personData(30,'Sue'),person.party将返回Sue,现在如果我将离婚()更改为if self.party!=无:自我。配偶=无。现在,如果我再次调用它,它应该会引发一个例外,即“没有配偶,离婚不可能”@user3259097是的,这是,除非我弄错了,否则如果你按照我的回答,你应该得到什么?我什么都没有得到,苏仍然是配偶,离婚()并没有删除苏。@user3259097你需要替换hasatt(self,'配偶'):
带有
self.party==None:
,在此之前不要添加它。如果这不是问题所在,请使用新代码更新您的答案。def divisions(self):If self.party==None:raise AttributeError,“未婚,离婚不可能”##我想做的是:#def divisions(self):#If self.party!#无:这意味着这个人有配偶,self.party=无我认为应该删除配偶,对吗##如果我们再次要求离婚,这应该是一个例外,因为配偶被除名了。