Thierry Lam
Thierry Lam

Reputation: 46264

Using Python's isinstance

The following usage of isinstance doesn't seem to work in Python 2.5.2 or 2.6.2:

class BananaCake:
    def __init__(self):
        print 'Banana Cake'

class ChocolateCake:
    def __init__(self):
        print 'Chocolate Cake'

class CakeFactory:
    @staticmethod
    def create(name):
        if name == 'banana':
            return BananaCake
        elif name == 'chocolate':
            return ChocolateCake
        else:
            return None

if __name__ == '__main__':
    banana_cake = CakeFactory.create('banana')
    print isinstance(banana_cake, BananaCake)

The above isinstance is returning False even though banana_cake is an instance of BananaCake. Does anyone know what I might be missing? I'm performing this check in my test scripts. You should be able to copy and paste the above and run it easily in a Python script.

Upvotes: 1

Views: 1810

Answers (2)

Georg Schölly
Georg Schölly

Reputation: 126095

You're returning a class instead of an instance.

>>> banana_cake is BananaCake
True

I believe you want this:

class CakeFactory:
    @staticmethod
    def create(name):
        if name == 'banana':
            return BananaCake()         # call the constructor
        elif name == 'chocolate':
            return ChocolateCake()      # call the constructor
        else:
            return None

To make isinstance()work with classes you need to define them as new-style classes:

class ChocolateCake(object):
    pass

You should declare all your classes as new-style classes anyway, there is a lot of extra functionality and old-style classes were dropped in Python 3.

Upvotes: 8

divegeek
divegeek

Reputation: 5023

That's because 'banana_cake' is not an instance of BananaCake.

The CakeFactory implementation returns the BananaCake CLASS, not an instance of BananaCake.

Try modifying CakeFactory to return "BananaCake()". Calling the BananCake constructor will return an instance, rather than the class.

Upvotes: 2

Related Questions