這里我定義了不可變類 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)
New 用于創建類實體。新方法的其他用途是什么?
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
new基本上是一個標準的 Python 方法,它在創建類實體時在init之前呼叫。有關更多資訊,請參閱 python新手冊:https : //docs.python.org/3/reference/datamodel.html#object.__new __
沒有其他直接用途。
關于Init/New的區別:python中的建構式叫new,init是初始化函式。根據 Python 檔案,new用于控制新實體的創建,而init用于處理其初始化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/378731.html
上一篇:不同型別繼承中的C new關鍵字
下一篇:如何從未指定的物件中獲取屬性?
