1

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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.