下面是一些python书籍中的一个示例:
import weakref
class CarModel:
_models = weakref.WeakValueDictionary()
def __new__(cls, model_name, *args, **kwargs):
"""
:type model_name: str
"""
model = cls._models.get(model_name)
if not model:
model = super().__new__(cls)
cls._models[model_name] = model
return model
def __init__(self, model_name, air=False, tilt=False, cruise_control=False, power_locks=False, alloy_wheels=False, usb_charger=False):
if not hasattr(self, "initted"):
self.model_name = model_name
self.air = air
self.tilt = tilt
self.cruise_control = cruise_control
self.power_locks = power_locks
self.alloy_wheels = alloy_wheels
self.usb_charger = usb_charger
self.initted = True
def check_serial(self, serial_number):
print("{0} not yet available on {1}".format(serial_number, self.model_name))
是否真的有必要检查对象是否已初始化?据我所知,__init__
函数无论如何只会被调用一次。你知道吗
这是一个有点奇怪的情况,因为它覆盖了新的,所以它可以在存储库中跟踪不同车型的汽车。你知道吗
所以你可以:
注意对
CarModel('ford')
的第二个调用实际上如何返回相同的对象(0x7fb39dfc1be0)?__新的uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。你知道吗需要注意的一点是,第二次传递的额外参数被完全忽略(因为它没有通过
not hasattr(self, "initted")
测试)。你知道吗相关问题 更多 >
编程相关推荐