Reputation: 406
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
Reputation: 452
for token in tokens:
if isinstance(token, Operator):
# do something
Upvotes: 1
Reputation: 770
Use method isinstance(token, Operator)
here is example
ar = Div()
if isinstance(ar, Operator):
print("true")
Upvotes: 1