这是我的密码:
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()
的时候,我会遇到一个例外,说“没有配偶”,如果我做不到这一点,任何帮助都将不胜感激。你知道吗
您没有直接引发异常,如果引发异常是所需的结果,那么这是适当的。(或者,您可以只打印一条消息,而不处理任何异常。)您不需要在这里使用
try
-except
。相反,只需提出异常,如:而且,您永远也无法访问当前的
try
部分,因为hasattr(self, 'spouse')
总是正确的。另一件事是,婚姻异常的发生是因为marries
的无限递归调用,而不是因为直接引发异常。您不应该从marries
内部调用marries
。你知道吗这将始终返回
True
,spouse
属性可能被设置为None
,但它仍然被设置。所以打印错误的else
分支将永远不会到达。你知道吗所以,你需要把它改成:
在
__init__
函数中,您正在执行:我只想跳过这个,将
self.spouse
设置为None
;这样就不需要getattr()
。你知道吗示例
由于您似乎对完整的解决方案有些困惑,下面是整个课程:
额外小费
在
marries()
函数中,您将执行以下操作:这是不正确的。这样做的目的是调用函数
marries()
(它不存在),将类实例self
和name
作为参数。你知道吗你想做的是:
这将调用类实例
self
上的函数marries()
。self
参数是由Python自动添加的,您不需要为简单的函数调用自己添加这个参数。你知道吗此错误未被注意到,因为您正在捕获所有异常。这些“必须全部捕获”的pokemon异常几乎总是一个坏主意,因为您捕获的不仅仅是您预期的错误,还有所有没有预期的错误,例如编程错误。你知道吗
(我也不明白为什么在这里使用递归?)你知道吗
相关问题 更多 >
编程相关推荐