首页 > 解决方案 > 创建新类实例的替代方法

问题描述

通常可以使用以下内容创建实例:

class New:
    def __new__(cls, *args, **kwargs):
        # placeholder
        return super().__new__(cls)
    def __init__(self, name):
        self.name = name

>>> n=New('bob')
>>> n
<__main__.New object at 0x103483550>

这里的幕后发生了什么?例如,类似:

new_uninitialized_obj = object.__new__(New)
new_initialized_obj = new_uninitialized_obj.__init__("Bob")

以上将不起作用,但我基本上只是想看看如何将基类型转换newinit实例对象。这实际上将如何完成?

标签: pythonpython-3.x

解决方案


__init__不返回任何内容,只会更新instance已在 中创建的__new__内容,因此您可以执行以下操作来创建新实例并对其进行初始化:

new_obj = object.__new__(New)
# We can see it creates a new object of class `New`
>>> new_obj
<__main__.New object at 0x103483e10>
>>> new_obj.__dict__
{}

new_obj.__init__("Bob")
# now we update the object attributes based on init
>>> new_obj.__dict__
{'name': 'Bob'}

推荐阅读