python - 创建新类实例的替代方法
问题描述
通常可以使用以下内容创建实例:
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")
以上将不起作用,但我基本上只是想看看如何将基类型转换new
为init
实例对象。这实际上将如何完成?
解决方案
__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'}
推荐阅读
- django - 多个表单的 CreateView form_invalid?
- mongodb - Mongodb Atlas Google Cloud 对等互连失败,本地网络中的 ip 范围与活动对等方中的 ip 范围重叠
- r - R中另一列中的组的列中的总和值
- python - 使用 pytest + Pycharm 处理长字符串的烦人差异格式
- android - 使用按钮和百分比填充投票投票 Android Kotlin
- reactjs - 在 NextJS 中重用父组件的导航
- python - 如何用reg exp拆分以下数据?
- python - 如何避免通过 Matplotlib 中的给定点绘制一条线?
- reactjs - 在使用带有 Google 地图的 Material-UI 自动完成时摆脱任何问题
- base64 - 如何修改机器人代码以发布 Teams 的 base64 图像