python 中 __new__ 方法的其他用途是什么?

sha*_*ila 6 python oop new-operator magic-methods

这里我定义了不可变类 str。在 方法中,我将“hello”等实例的值更改为大写。当我们可以在init中定义 upper 时,为什么要使用new来实现呢?

class Upperstr(str):
    def __new__(cls,value=""):
        print(cls)
        print(value)
        return str.__new__(cls,value.upper())

    # def __init__(self,m1):
    #     self.m1 = m1.upper()
    
u = Upperstr("hello")
print(u)

Run Code Online (Sandbox Code Playgroud)

New 用于创建类实例。方法还有哪些其他用途?

Daw*_*weo 8

New 用于创建类实例。方法还有哪些其他用途 ?

您可以使用它__new__来实现单例模式(其中模式必须理解为设计模式:可重用面向对象软件的元素中描述的内容),请查看geeksforgeeks.org提供的经典单例示例

class SingletonClass(object):
  def __new__(cls):
    if not hasattr(cls, 'instance'):
      cls.instance = super(SingletonClass, cls).__new__(cls)
    return cls.instance
   
singleton = SingletonClass()
new_singleton = SingletonClass()
 
print(singleton is new_singleton)
 
singleton.singl_variable = "Singleton Variable"
print(new_singleton.singl_variable)
Run Code Online (Sandbox Code Playgroud)


Sim*_*ost -2

new基本上是一个标准的 Python 方法,在创建类实例时在init之前调用。有关更多信息,请参阅 python new手册: https://docs.python.org/3/reference/datamodel.html#object.__new __

它没有其他直接用途。

关于Init/New的区别:python中的构造函数称为newinit是初始化函数。根据Python文档,new用于控制新实例的创建,而init用于处理其初始化。