Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否有必要检查flyweight模式中的初始状态?_Python_Design Patterns - Fatal编程技术网

Python 是否有必要检查flyweight模式中的初始状态?

Python 是否有必要检查flyweight模式中的初始状态?,python,design-patterns,Python,Design Patterns,下面是一些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)

下面是一些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))

是否确实需要检查对象是否已初始化?就我所见,
\uuuuu init\uuuuuuuuuuuuuuuu
函数无论如何只会被调用一次。

这是一个有点奇怪的情况,因为它覆盖了“new”\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

因此,您可以:

c = CarModel('ford')
<cars.CarModel at 0x7fb39dfc1be0>

c = CarModel('vw')
<cars.CarModel at 0x7fb39df72668>

c = CarModel('ford')
<cars.CarModel at 0x7fb39dfc1be0>
c=CarModel('ford'))
c=CarModel(“vw”)
c=汽车模型(‘福特’)
注意对
CarModel('ford')
的第二次调用实际上是如何返回相同的对象的(0x7fb39dfc1be0)__new_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

需要注意的是,第二次传递的额外参数被完全忽略(因为它未通过
nothasattr(self,“initted”)
测试)