__new__ 类静态方法
# coding=utf-8# python 3.7
class A:
__newObject = None # 类字段
def __new__(cls, name, age): # 创建类型 A 的实例
print(f"类型 A 的地址:{id(cls):#X}")
if A.__newObject is None: # 第二次访问就不会创建新的实例,直接返回之前的实例
A.__newObject = super().__new__(cls) # super(A, A).__new__(cls) 相同
return A.__newObject
def __init__(self, name, age): # 初始化字段
self.Name = name
self.Age = age
self.__x = 0
def Display(self):
print(f"A 实例的地址:{id(self):#x} Name = {self.Name} Age = {self.Age}")
test = A("G", 2)
test.Display()
test1 = A("H", 1)
test1.Display()
if test == test1:
print("Equ")
# 类型 A 的地址:0XC9A968
# A 实例的地址:0xc98a10 Name = G Age = 2
# 类型 A 的地址:0XC9A968
# A 实例的地址:0xc98a10 Name = H Age = 1
# Equ 确实比Java简单一点 __new__ 方法多用于metaclass
页:
[1]