I've got a main "abstract" class Pet, and two "real" classes Dog and Cat. When I've got two instances of pets, I want to know if they are the "same kind of pets" without taking care of what kind of pets they are.
I tried this
#!/usr/bin/python
class Pet:
name = "pet"
def __eq__(self, other):
return type(self) == type(other)
# return type(self).__name__ == type(other).__name__
# return self.__class__ == other.__class__
# return self.__class__.__name__ == other.__class__.__name__
# return self.__class__ is other.__class__
# return self.__class__.__name__ is other.__class__.__name__
# return isinstance(other, type(self).__name__)
# return isinstance(other, type(self))
# return isinstance(self, type(other).__name__)
# return isinstance(self, type(other))
# return type(self) is type(other)
# return type(self).__name__ is type(other).__name__
class Dog:
name = "dog"
class Cat:
name = "cat"
dog1 = Dog()
dog2 = Dog()
cat1 = Cat()
cat2 = Cat()
print("dog1 == dog2: {0}".format(dog1 == dog2))
print("cat1 == cat2: {0}".format(cat1 == cat2))
print("cat1 == dog1: {0}".format(cat1 == dog1))
I tried all the commented return, and it always gives this result:
$ ./test.py
dog1 == dog2: False
cat1 == cat2: False
cat1 == dog1: False
I guess it's because it consider the first operand as a Pet
because the method is in this class.
Is there a way to such a test in the main class to avoid code duplication?
EDIT:
As multiple people mentioned it forgot the subclassing part...
This works as intended
#!/usr/bin/python
class Pet:
name = "pet"
def __eq__(self, other):
return self.__class__ == other.__class__
class Dog(Pet):
name = "dog"
class Cat(Pet):
name = "cat"