Home > other >  in python how to check object type inside a class for class comparison
in python how to check object type inside a class for class comparison

Time:09-17

I create a class in python and I would like to create a comparison method to compare instances of the same class.

As such:

class A():
    def __init__(self,a):
        self.var = a
        
    def comparison(self,other):
        if not isinstance(other,self):  # <<--- ERROR HERE
            raise Exception("You are not comparing apples to apples")
        else:
            if self.var==other.var:
                print('we are equal')
            else:
                print('we are different')

This foes not fly.

The intended used would be like:

first  = A(8)
second = A(9)
third  = A(8)
fourth = ['whatever']

first.comparison(second) # should give "different"
first.comparison(third)  # should give "equal"
first.comparison(fourth) # should raise error

the method comparison should raise an exception if the user passes something different than another instance of the same class, and make the comparison if they both are instances of the same class. How to proceed?

Thx.

CodePudding user response:

Try this instead of isinstance, isinstance(other, A) would also be True for subclasses of A.

    def comparison(self,other):
        if type(self) is not type(other):
            raise "You are not comparing apples to apples"

CodePudding user response:

your instance is not self, but it is A.

If you change this line:

if not isinstance(other,self):

to this:

if not isinstance(other,A):

Or to this:

if not isinstance(other,type(self)):

it works fine.

  • Related