【发布时间】: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