- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个用于测试的单例装饰器,但是当我询问一个对象是否是原始类的实例时,它返回 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
最佳答案
您可以使用 singleton
Python Decorator Library 中的类装饰器.
它之所以有效,是因为它修改了现有的类(替换 __new__()
方法),而不是像您问题中的代码中那样用完全独立的类替换它。
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
关于python - 如何使类装饰器不破坏 isinstance 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55345243/
Integer.class、int.class 和 Integer.TYPE 之间有什么区别?我对这三者有点困惑。 最佳答案 i 是 int 还是 Integer: Integer.class.isI
a='aaaa' print isinstance(a, basestring)#true print isinstance(a, str)#true 最佳答案 在 3.0 之前的 Python 版本
我有一个名为 Route 的类(具有自己的 __repr__() 函数),以及一个名为 default_route 的 Route 实例。但是,如果我调用 isinstance(default_rou
以下是我的代码,可以正常编译,但在运行时遇到案例 2 的 ClassNotFoundException ,我的问题是为什么我在案例 2 中遇到错误: 案例1 命令java Var Var 输出假 案例
我使用 scrapy 0.20 和 python 2.7 这是我的代码 def process_spider_output(self, response, result, spider): p
Python 深入“PyPDF2.generic.Destination”的嵌套列表并列出对象以到达列表的最后一个实例的最有效方法是什么?(获取 PDF 大纲的所有级别及其页码)。 pdfread =
我观察到一个涉及对象“AuditResult”的奇怪现象,我希望有人能帮助我理解。我有一个这样设置的模块: model\ __init__.py common.py (AuditResult
我对 isinstance() 在 Python 中的工作方式有些迷惑。我以前用过这个函数,直到现在,行为还是很清楚的。 一些上下文。我有一个 Classifier 类,它有一个方法 set_kern
此代码来自 python cook book 第 3 版,来自 classes chapter section 8.13 。该程序试图定义各种数据结构,但希望对允许分配给某些属性的值实现约束。我正在使
我有一个我写的类,MyEdge(它存储两个节点来为某些图形创建边),我正在努力弄清楚为什么 isinstance 似乎表现不一致。 我有一个对象 new_road,当我询问它时,它认为它在 MyEdg
如果任何参数是 np.ndarray,我有一个函数需要采用不同的路径。我正在检查 isinstance .但我想知道是否有比将列表理解与 any 一起使用更直观(和更快)的方法: def func(a
某些类在类级别(在 __init__ 或任何其他函数之外)定义其属性(也称为字段)。有些类在其 __init__ 函数中定义它们,甚至从其他函数中定义它们。有些类(class)同时使用这两种方法。 c
我正在更改单元测试涵盖的一些代码。在单元测试中会发生这样的事情: def create_object(cls, arg1=None, arg2=None, arg3=None, **kwargs):
我不明白为什么 isinstance 函数作为第二个参数需要一个元组而不是一些可迭代的? isinstance(some_object, (some_class1, some_class2)) 工作正
def convBin(): cont = [] rest = [] dev = [] decimal = [] print("Give me a number
我定义了一个 Time 类,它具有三个 int 属性:hrs、min、sec 然后我定义了方法 intToTime() 将 Time 实例转换为 int,这是当时的秒数,还有一个执行相反操作的方法 t
我在模块 Factor.py ( https://github.com/pgmpy/pgmpy/blob/dev/pgmpy/factors/Factor.py ) 中有一个名为 Factor 的类,
type()函数: 使用type()函数可以判断对象的类型,如果一个变量指向了函数或类,也可以用type判断。 如: python" id="highl
当处理整数时,有多种类型可用(例如 int、numpy.int8、numpy.int16 等)。如果我编写一个要求一个变量为整数的通用函数,我如何针对 Python/numpy 中所有可能的“整数”类
(编辑标题,因为答案适用于任何类,而不仅仅是 cython 类) 我正在开发对性能有非常严格限制的扩展类型,我对结果很满意。 我发现对于基本上是限制为 0 < 值 < 360 的 float 的类型,
我是一名优秀的程序员,十分优秀!