Djbur14
Djbur14

Reputation: 11

Comparing two created objects in Python

I have a class DooDadX that is inheriting from another class DooDad. I'm trying to look at the left hand side, self, and if it is a DooDadX instance it will be a different color.

The main problem I am having is I need to find out if self, in __mod__, is a DooDadX instance or not. If it is, the color will be green, if it's not, the color will be from my inherited class.

In my test code I have DooDadX being called on the left side. This should change the color to green but I am getting the color blue.

I could link all of my code but it's about 114 lines with the test code. If this isn't sufficient please let me know.

class DooDadX(DooDad):
    def __init__(self, color, weight, value):
        super().__init__(color, weight, value)
        self._serial = "-" + str(self._serial)
        self._name = " DooDadX "


    def __mod__(self, other):
        if self == DooDadX:
            self._color = "green"
        maxWeight = max(self._weight, other._weight)
        rightValue = other._weight
        newDooDadX = DooDadX(self._color, maxWeight, rightValue)
        return newDooDadX

This is my test code.

    if __name__=="__main__":
        doodads = []
        doodads.append(DooDad("red", 5, 10))
        doodads.append(DooDad("red", 8, 9,))
        doodads.append(DooDad("blue", 20, 15))
        doodads.append(DooDad("green", 2, 5))
        doodads.append(DooDadX("blue", 10, 12))
        doodads.append(doodads[0] + doodads[1])
        doodads.append(doodads[2] + doodads[0])
        doodads.append(doodads[3] - doodads[1])
        doodads.append(doodads[1] - doodads[3])
        doodads.append(doodads[0] * doodads[1])
        doodads.append(doodads[0] * doodads[2])
        doodads.append(doodads[0] / doodads[3])
        doodads.append(doodads[2] % doodads[4])
        doodads.append(doodads[4] % doodads[2])

        for doodad in doodads:
            print(doodad)

Upvotes: 0

Views: 86

Answers (2)

pzp
pzp

Reputation: 6597

If you want to test if self is an instance of DooDadX or if it is an instance of any inherited class of DooDadX, do as @Joe recommended. If you want to test if self is ONLY an instance of DooDadX use type() as such:

if type(self) == DooDadX

Hope that this slight distinction is helpful.

Upvotes: 1

Joe
Joe

Reputation: 2564

Change this:

if self == DooDadX:

by this:

if isinstance(self, DooDadX):

Upvotes: 1

Related Questions