Glitch
Glitch

Reputation: 406

How to check type of a subclass using the parent class in python?

Let's say I have five classes represented like this:

class Operator:
    def __init__(self):
        pass

class Pow(Operator):
    pass

class Mul(Operator):
    pass

class Div(Operator):
    pass

class Add(Operator):
    pass

class Sub(Operator):
    pass

And an array of tokens some of them are numbers and the others are objects instantiated from the classes above {Pow, Mul, Div, Add, Sub}.

When I loop through the array, I want to be able to check for the type of token like this:

for token in tokens:
    if type(token) is Operator:
        # do something

Instead of doing this:

for token in tokens:
    if type(token) in [Pow, Mul, Div, Add, Sub]:
        # do something

I don't know if there is a good alternative for the second for loop.

(Any code refactoring is welcomed)

Upvotes: 0

Views: 1078

Answers (2)

zuijiang
zuijiang

Reputation: 452

for token in tokens:
    if isinstance(token, Operator):
        # do something

Upvotes: 1

How about nope
How about nope

Reputation: 770

Use method isinstance(token, Operator)

here is example

ar = Div()
if isinstance(ar, Operator):
    print("true")

Upvotes: 1

Related Questions