问题
I have a Class in python, with the following attributes:
self.number1 = 0 self.number2 = 0 self.divided = self.number1/self.number2
This of course throws up the zero error:
ZeroDivisionError: integer division or modulo by zero
The idea is that I will increment number1 and number2 later on, but will self.divided be automatically updated? If it is auto updated then how do I get around the zero error? Thanks.
回答1:
No, self.divided
is a simple attribute and will not automatically update. For dynamic attributes, use a property instead:
class Foo(object):
number1 = 0
number2 = 0
@property
def divided(self):
return self.number1 / self.number2
回答2:
Automatic update with avoidance of ZeroDivisionError:
@property
def divided(self):
try:
#suppose that number2 is a float
return self.number1/self.number2
except ZeroDivisionError:
return None
回答3:
You can do the following in single as I have shown:
self.divided = self.number1/(self.number2 or not self.number2)
this ensures that if your value is 0, you don't get the error. But be sure, use this only if you are using integer values or values which are greater than 1.
来源:https://stackoverflow.com/questions/13646347/python-divide-by-zero-error