Python error exception handling

this is my code:

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"

I am trying to do the following:

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?

An exception should appear here if we call the divorce again because the spouse has been removed.

Say mine:

person = personData(30, 'Sue')

person.spousethere will be Sue, if I call person.marries('Anna'), an exception occurs, now, if I call person.divorce(), he will delete the spouse ( 'Sue'). what I’m stuck with is when I call person.divorce(), he should make an exception saying that “no spouse exists”, and I can’t do this, any help will be appreciated.

+3
source share
2 answers

, , . ( - .) try - except . , :

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

, try, hasattr(self, 'spouse') . , - marries, - . marries marries.

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

True, spouse 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() ( ) self name .

:

self.marries(name)

marries() self. self Python, .

, . "Gotta catch" em - , , , , , .

( , ?)

+2

All Articles