【发布时间】:2019-03-25 19:37:57
【问题描述】:
我正在为测试创建一个单例装饰器,但是当我询问一个对象是否是原始类的实例时,它返回 false。
在示例中,我装饰了一个计数器类来创建一个单例,所以每次如果我得到值,它就会返回下一个数字,无论对象的哪个实例调用它。 代码几乎可以工作,但函数 isinstance 似乎坏了,我尝试使用 functools.update_wrapper 但我不知道我是否可以让 isinstance 函数将 Singleton 识别为 Counter (在下面的代码中),只要我要求 Counter代码实际上返回 Singleton。
装饰器
def singleton(Class):
class Singleton:
__instance = None
def __new__(cls):
if not Singleton.__instance:
Singleton.__instance = Class()
return Singleton.__instance
#update_wrapper(Singleton, Class,
# assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotation__'),
# updated=()) #doesn't seems to work
return Singleton
装饰类
@singleton
class Counter:
def __init__(self):
self.__value = -1
self.__limit = 6
@property
def value(self):
self.__value = (self.__value + 1) % self.limit
return self.__value
@property
def limit(self):
return self.__limit
@limit.setter
def limit(self, value):
if not isinstance(value, int):
raise ValueError('value must be an int.')
self.__limit = value
def reset(self):
self.__value = -1
def __iter__(self):
for _ in range(self.limit):
yield self.value
def __enter__(self):
return self
def __exit__(self,a,b,c):
pass
测试
counter = Counter()
counter.limit = 7
counter.reset()
[counter.value for _ in range(2)]
with Counter() as cnt:
print([cnt.value for _ in range(10)]) #1
print([counter.value for _ in range(5)]) #2
print([val for val in Counter()]) #3
print(Counter) #4
print(type(counter)) #5
print(isinstance(counter, Counter)) #6
输出:
#1 - [2, 3, 4, 5, 6, 0, 1, 2, 3, 4]
#2 - [5, 6, 0, 1, 2]
#3 - [3, 4, 5, 6, 0, 1, 2]
#4 - <class '__main__.singleton.<locals>.Singleton'>
#5 - <class '__main__.Counter'>
#6 - False
(未注释更新包装器)
#1 - [2, 3, 4, 5, 6, 0, 1, 2, 3, 4]
#2 - [5, 6, 0, 1, 2]
#3 - [3, 4, 5, 6, 0, 1, 2]
#4 - <class '__main__.Counter'>
#5 - <class '__main__.Counter'>
#6 - False
【问题讨论】:
-
在 Python 2 上,如果你说
class Singleton(Class),它就可以工作。不知道为什么它在 Python 3 上不能正常工作,但也许这可以引导你到那里? -
我已经尝试从类、对象和各种(如果不是全部)两者的组合继承,其中任何一个似乎都可以工作 x.x
标签: python python-3.x singleton decorator