Search code examples
pythonfunctionclasspython-2.7instanceof

Confirming class instantiation with return value in function


New to Python, so bear with me...

Given the following function (and assuming the class referenced here is created properly):

def next_scene(scene_name):
    print scene_name
    scenes = {'Chip_in_the_car': ChipCar(), 'Chip_in_the_studio': ChipInStudio(), 'Chip_mom_house': ChipMomHouse(), 'Chip_at_rehearsal': SickFuckingPuppies(), 'Death': Death()}

    for key, value in scenes.iteritems():
        if scene_name == key:
            print value
            return value

Ok, so what's returned here as value is the following:

<__main__.ChipCar object at 0x104503390>

Does that now mean that an instance of the ChipCar class has been instantiated or is it simply just returning the class as an object's place in memory? How can I use this function to create an instance of that ChipCar class?

Thanks for any insight (sure this is a noob question).


Solution

  • Yes, you have an instance of the class. You are looking at the default __repr__ return value for instances, which includes the module name, the class name and the id() value of the object expressed as hexadecimal.

    You can give your class a custom __repr__ method to alter that text, it should return a string that is useful when debugging. For example:

    >>> class ChipCar(object):
    ...     def __repr__(self):
    ...         return '{}() object, id => 0x{:x}'.format(type(self).__name__, id(self))
    ... 
    >>> ChipCar()
    ChipCar() object, id => 0x1046c33d0