在函数中使用 return 值确认 class 实例化

Confirming class instantiation with return value in function

Python 的新手,所以请多多包涵...

给定以下函数(并假设此处引用的 class 已正确创建):

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

好的,所以这里作为 value 返回的内容如下:

<__main__.ChipCar object at 0x104503390>

这是否意味着 ChipCar class 的一个实例已经被实例化,或者它只是将 class 作为对象在内存中的位置返回?我如何使用此函数创建 ChipCar class 的实例?

感谢您的任何见解(确定这是一个菜鸟问题)。

是的,您有一个 class 的实例。您正在查看实例的默认 __repr__ return 值,其中包括模块名称、class 名称和以十六进制表示的对象的 id() 值。

您可以为您的 class 自定义 __repr__ 方法来更改该文本,它应该 return 一个在调试时有用的字符串。例如:

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