When creating a class, how do I compare the class(type) object that is being created in the __eq__ function?

Asked 2 years ago, Updated 2 years ago, 97 views

For example,


class num 

    def __init__(self,input_parm):
        self.num = int(input_parm)

    def __eq__(self, other):

In this case (switch the input to an integer and store it as an initialization value) When input parameter (input_parm) can receive str, int, and num types

When receiving num type as input parameter, it is the same as receiving int and str type Just self.Can I do num = int(input_num)?

And in the __eq__ part, When num type enters other

self.num == other.num
return True

Is it okay to do this?

I don't know how to code when input parameters come in with the same type.

python class

2022-09-22 18:04

1 Answers

I don't know the purpose, but the __eq__ magic method is simple, so I think the example below would be enough.

class My:
    def __init__(self, v):
        self.v = v

    def __eq__(self, other):
        return (self.__class__ == other.__class__ ) and (self.v == other.v)

class ScarceMy:
    def __init__(self, v):
        self.v = v

    def __eq__(self, other):
        return self.v == other.v


s_my1 = ScarceMy(10)
s_my2 = ScarceMy(20)

my1 = My(10)

print(s_my1 == s_my2) # This is a different value, so of course it's false
print(s_my1 == my1) # It is false to expect because it is not an object of the same class, but it is true because it only compares values
print(my1 == s_my1) # False as expected by checking if it is the same class


2022-09-22 18:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.