Python Divide By Zero Error

两盒软妹~` 提交于 2019-12-10 17:17:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!