Home > Software engineering >  Getting an Exception even though class attribute is correct type
Getting an Exception even though class attribute is correct type

Time:07-09

I am currently working on a project that has the following class

    import operator

    class dummy:
    def __init__(self,
                 density):
        self.density = density
    
    density = property(operator.attrgetter('_density'))

    @property
    def density(self):
        return self._density
    
    @density.setter
    def density(self,value):
        if type(value) != int or type(value) != float:
            raise Exception("density must be int or float types!")
        elif value <= 0:
            raise Exception("density must be non-zero and positive!")
        self._density = value

I am getting an Exception whenever I try to run this code like so:

dev = dummy(density = 3.25)

This is the error I get:

----> 1 dev = dummy(density = 3.25)

~\AppData\Local\Temp/ipykernel_18292/2065730148.py in __init__(self, density)
      2     def __init__(self,
      3                  density):
----> 4         self.density = density
      5 
      6     density = property(operator.attrgetter('_density'))

~\AppData\Local\Temp/ipykernel_18292/2065730148.py in density(self, value)
     13     def density(self,value):
     14         if type(value) != int or type(value) != float:
---> 15             raise Exception("density must be int or float types!")
     16         elif value <= 0:
     17             raise Exception("density must be non-zero and positive!")

Exception: density must be int or float types!

I don't know what I'm doing wrong here. Any help would be greatly appreciated!

CodePudding user response:

If it's a float, then type(value) != int will evaluate true, and you'll raise the exception.

Change the logic to "and" and it will work:

if type(value) != int and type(value) != float:
  • Related