gpt4 book ai didi

Python __new__ - cls 如何与 __new__ 所在的类不同

转载 作者:行者123 更新时间:2023-12-01 03:48:04 25 4
gpt4 key购买 nike

Documentation for object.__new__(cls[, ...]) says:

Called to create a new instance of class cls. __ new __ is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument.

因此,如果您有 var = MyClass()

class MyClass:
def __new__(cls):
...

cls 不会总是等于 MyClass 吗?

最佳答案

试试这个:

class MyClass:
def __new__(cls):
print(cls)

class Yac(MyClass):
pass

x = Yac()
print(x)

我们得到:

<class '__main__.Yac'>
None

顺便说一下,这在 Python 3 中没问题,但在 Python 2 中不起作用。在 Python 2 中,__new__ 仅在“新式”类中受支持:

class MyClass(object):

在 Python 3 中,所有类都是“新式”的。

关于Python __new__ - cls 如何与 __new__ 所在的类不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38661030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com