The Python way to test for the type of an object is to use isinstance, as in isinstance(tom,Writer)
.
But whenever you start to write code that reads like your example, think about using polymorphism instead. Here is a simple class hierarchy that does what you want, without a single call to isinstance:
class Worker(object):
def __init__(self, name):
self.name = name
def is_doing(self):
return "working"
class Writer(Worker):
def is_doing(self):
return "writing"
class Programmer(Worker):
def is_doing(self):
return "programming"
workers = [
Writer("Tom"),
Programmer("Dick"),
]
for w in workers:
print "%s is %s" % (w.name, w.is_doing())
Prints:
Tom is writing
Dick is programming
Now you can just add new subclasses to Worker and implement is_doing, and you don't have to maintain some table of type-to-activity values.
This pattern of polymorphism is traditional O-O, but in Python, you aren't even restricted to subclasses of Worker - any object that implements is_doing
and has a name
attribute will work:
class Fish(object):
def __init__(self, n):
self.name = n
def is_doing(self):
return "swimming"
workers.append(Fish("Wanda"))
for w in workers:
print "%s is %s" % (w.name, w.is_doing())
will print:
Tom is writing
Dick is programming
Wanda is swimming