我试图实现单班为我的项目和一个有趣的帖子在StackOverflow上在同一元类可以有方法吗?
Creating a singleton in Python
我决定去与方法中提到的元类..
现在..我试着添加一个方法来获取和清除实例(如果用户希望摆脱当前实例,并创建一个新的..):
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]
def getInstance(cls):
print("Class is {}".format(cls.__name__))
if not cls in cls._instances:
raise LookupError("No instance of the class {cls} create yet.".format(cls.__name__))
return cls._instances[cls]
def clearInstance(cls):
cls._instances.pop(cls, None)
class someClass(metaclass=Singleton):
def __init__(self,val):
self.value = val
我能够创建OBJ学分顺利..
In [9]: sc = someClass(1)
In [10]: sc.value
Out[10]: 1
但是当我做dir(someClass)
不显示2种方法:
In [14]: dir(someClass)
Out[14]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__']
不过我能够调用的方法..
In [13]: someClass.getInstance()
Class is someClass
Out[13]: <__main__.someClass at 0x7f728b180860>
在元类的所有例子中,我在网上看到我看到__new__
,__init__
和__call__
方法实现,但我没有看到任何额外的方法添加。将方法添加到元类是否正确?
我还试图上述元类代码的微小变化:
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]
@classmethod
def getInstance(cls):
print("Class is {}".format(cls.__name__))
if not cls in cls._instances:
raise LookupError("No instance of the class {cls} create yet.".format(cls.__name__))
return cls._instances[cls]
@classmethod
def clearInstance(cls):
cls._instances.pop(cls, None)
标记2种方法作为类方法..
现在,当我尝试调用它们:
In [2]: sc = someClass(1)
In [3]: someClass.getInstance()
Class is Singleton
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-3-c83fe01aa254> in <module>()
----> 1 someClass.getInstance()
<ipython-input-1-9efb6548d92d> in getInstance(cls)
12
13 if not cls in cls._instances:
---> 14 raise LookupError("No instance of the class {cls} create yet.".format(cls.__name__))
15
16 return cls._instances[cls]
KeyError: 'cls'
正如你可以看到class is
打印说,其Singleton
当我装饰它为classmethod
。否则它显示正确的类。我不明白这种行为,有人可以解释吗?
虽然我同意他们可以有方法,但也有人问:“向元类添加方法是否正确?” - 这有点难以回答。我肯定会对你的想法在这一点上感兴趣:) – MSeifert