如何使 class 装饰器不破坏 isinstance 函数?

How can I make a class decorator not break isinstance function?

我正在为测试创建一个单例装饰器,但是当我询问一个对象是否是原始对象的实例时 class 它 returns false。

在这个例子中,我正在装饰一个计数器 class 来创建一个单例,所以每次如果我得到它的值 returns 下一个数字,无论对象的哪个实例调用它. 代码几乎可以正常工作,但是函数 isinstance 似乎中断了,我尝试使用 functools.update_wrapper 但我不知道我是否可以获得 isinstance 函数来将 Singleton 识别为 Counter(在下面的代码中),只要我问对于 Counter 代码实际上 returns 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

装饰class

@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

您可以使用 singleton class decorator in the Python Decorator Library.

之所以有效,是因为它修改了现有的 class(替换了 __new__() 方法),而不是像您问题的代码中那样用完全独立的 class 替换它.

import functools

# from https://wiki.python.org/moin/PythonDecoratorLibrary#Singleton
def singleton(cls):
    ''' Use class as singleton. '''

    cls.__new_original__ = cls.__new__

    @functools.wraps(cls.__new__)
    def singleton_new(cls, *args, **kw):
        it =  cls.__dict__.get('__it__')
        if it is not None:
            return it

        cls.__it__ = it = cls.__new_original__(cls, *args, **kw)
        it.__init_original__(*args, **kw)
        return it

    cls.__new__ = singleton_new
    cls.__init_original__ = cls.__init__
    cls.__init__ = object.__init__

    return cls

有了它,我得到以下输出(注意最后一行):

[2, 3, 4, 5, 6, 0, 1, 2, 3, 4]
[5, 6, 0, 1, 2]
[3, 4, 5, 6, 0, 1, 2]
<class '__main__.Counter'>
<class '__main__.Counter'>
True

并不比上面的更好,但如果您以后需要凭记忆执行此操作,则稍微简单且更容易记住:

def singleton(Class, *initargs, **initkwargs):
    __instance = Class(*initargs, **initkwargs)
    Class.__new__ = lambda *args, **kwargs: __instance
    Class.__init__ = lambda *args, **kwargs: None
    return Class