【问题标题】:How can show the singleton object's attribution?如何显示单例对象的属性?
【发布时间】:2021-10-12 15:08:41
【问题描述】:

我们可以通过dir函数显示实例的归属。

>>> class mytest():
...     test = 1
...     def __init__(self):
...         pass
>>> x=mytest()
>>> x.test
1
>>> dir(x)[-1]
'test'

现在用元类方法创建一个类:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Cls(metaclass=Singleton):
    pass

显示 Cls 的_instances 属性:

Cls._instances
{<class '__main__.Cls'>: <__main__.Cls object at 0x7fb21270dc40>}

为什么dir(Cls) 中没有字符串_instances

>>> dir(Cls)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__',  
 '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', 
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', 
'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', '__weakref__']
>>> Cls.__dict__
mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Cls' objects>, 
'__weakref__': <attribute '__weakref__' of 'Cls' objects>, '__doc__': None})    

【问题讨论】:

    标签: python python-3.x class


    【解决方案1】:

    因为它存储在元类中。

    >>> '_instances' in dir(Singleton)
    True
    >>> Singleton._instances
    {<class '__main__.Cls'>: <__main__.Cls object at 0x7fb21270dc40>}
    

    需要明确的是,这与单例方面无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      相关资源
      最近更新 更多