Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting an Exception even though class attribute is correct type

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading