[英]Best way to check if a partial(Class) is an instance of Class
So here's my setup:所以这是我的设置:
from functools import partial
class MyClass:
def __init__(self, some_kwarg=0):
pass
def func(class):
# VERSION 1: I don't do anything
# VERSION 2: I do this
class = partial(class, some_kwarg=1)
# check if class points to MyClass
### THIS is where I want your input stack overflow
So there are a few things going on here for me:所以这里有一些事情对我来说:
class == MyClass
?class == MyClass
吗?partial
.partial
. My naive solution is class.func == MyClass
class.func == MyClass
(class == MyClass or (isinstance(class, partial) and partial.func == MyClass))
(class == MyClass or (isinstance(class, partial) and partial.func == MyClass))
Firstly, class
is a reserved word, so I'll use class_
instead (per PEP8 ).首先,
class
是一个保留字,所以我将使用class_
代替(根据PEP8 )。
Use is
instead of ==
, to check identity instead of equality (though they'll usually be the same when dealing with class objects).使用
is
而不是==
来检查身份而不是相等(尽管在处理类对象时它们通常是相同的)。
class_ is MyClass
Or, if you need to account for subclasses, use issubclass()
, which includes the case where class_ is MyClass
.或者,如果您需要考虑子类,请使用
issubclass()
,其中包括class_ is MyClass
的情况。
issubclass(class_, MyClass)
See point 1, just replace class_
with class_.func
.参见第 1 点,只需将
class_
替换为class_.func
。
You're on the right track.你在正确的轨道上。 I would just try to flatten out that nested expression, maybe like this:
我只是试着把那个嵌套的表达式弄平,也许是这样的:
departial = class_.func if isinstance(class_, partial) else class_ departial is MyClass
Example:例子:
from functools import partial
class MyClass:
pass
for class_ in MyClass, partial(MyClass), range, partial(range):
departial = class_.func if isinstance(class_, partial) else class_
result = departial is MyClass
print(result, class_)
Output:输出:
True <class '__main__.MyClass'>
True functools.partial(<class '__main__.MyClass'>)
False <class 'range'>
False functools.partial(<class 'range'>)
MyClass
is callable, and returns an instance of MyClass
when called. MyClass
是可调用的,并在调用时返回MyClass
一个实例。
partial
just wraps MyClass
in a callable object that, when called, calls MyClass
with some predetermined arguments. partial
只是将MyClass
包装在一个可调用对象中,当被调用时,它会使用一些预先确定的参数调用MyClass
。
partial(MyClass)()
, by definition , will return an instance of MyClass
. partial(MyClass)()
,根据定义,将返回MyClass
一个实例。 You don't need to check.你不需要检查。
(While it's possible to override MyClass.__new__
to return something other than an instance of MyClass
, that's not something you would need to check because of partial
.) (虽然可以覆盖
MyClass.__new__
以返回MyClass
实例以外的其他内容,但由于partial
您不需要检查这些内容。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.