gpt4 book ai didi

Python __new__ dundor 方法

转载 作者:行者123 更新时间:2023-12-02 02:17:20 25 4
gpt4 key购买 nike

我有下面的代码,我理解__new__用于创建一个类的实例,__init__方法用于初始化对象的值.

__init__ 是否只在返回基类的实例时调用?

我想要的是返回另一个类 A 的实例。有没有办法让__init__配置A类的实例?

# Python program to
# demonstrate __new__ method

# class whose object
# is returned
class GeeksforGeeks(object):
def __str__(self):
return "GeeksforGeeks"

# class returning object
# of different class
class Geek(object):
def __new__(cls):
return GeeksforGeeks()

def __init__(self):
print("Inside init")

print(Geek())
Output:

GeeksforGeeks

最佳答案

docs 中所述:

If __new__() is invoked during object construction and it returns aninstance or subclass of cls, then the new instance’s __init__()method will be invoked like __init__(self[, ...]), where self isthe new instance and the remaining arguments are the same as werepassed to the object constructor.

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.

所以不,它不会被调用。您可以自己手动调用它。

关于Python __new__ dundor 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66967354/

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