标签: isinstance

正确使用`isinstance(obj,class)`

在我写这篇文章的时候,对我来说,我实际上遇到了这个问题.

我有一个对象列表.这些对象中的每一个都是Individual我编写的类的实例.

因此,传统智慧说isinstance(myObj, Individual)应该回归True.但事实并非如此.所以我认为我的编程中存在一个错误并打印出来type(myObj),令我惊讶的是打印instancemyObj.__class__给了我Individual!

>>> type(pop[0])
<type 'instance'>
>>> isinstance(pop[0], Individual) # with all the proper imports
False
>>> pop[0].__class__
Genetic.individual.Individual
Run Code Online (Sandbox Code Playgroud)

我很难过!是什么赋予了?

编辑:我的个人课程

class Individual:
    ID = count()
    def __init__(self, chromosomes):
        self.chromosomes = chromosomes[:]    # managed as a list as order is used to identify chromosomal functions (i.e. chromosome i encodes functionality f)
        self.id = self.ID.next()

    # other methods
Run Code Online (Sandbox Code Playgroud)

python class isinstance

8
推荐指数
1
解决办法
4908
查看次数

用于pygame中的MVC事件处理的Python duck-typing

我和朋友一直在玩pygame,并且遇到了使用pygame 构建游戏的教程.我们真的很喜欢它如何将游戏分解为模型 - 视图 - 控制器系统,其中事件作为中间人,但代码大量使用isinstance事件系统的检查.

例:

class CPUSpinnerController:
    ...
    def Notify(self, event):
        if isinstance( event, QuitEvent ):
            self.keepGoing = 0
Run Code Online (Sandbox Code Playgroud)

这导致一些非常非常规的代码.有没有人对如何改进这方面有任何建议?或者实施MVC的替代方法?


这是我根据@ Mark-Hildreth答案编写的一些代码(如何链接用户?)其他人有什么好的建议吗?在选择解决方案之前,我将在另一天左右开放.

class EventManager:
    def __init__(self):
        from weakref import WeakKeyDictionary
        self.listeners = WeakKeyDictionary()

    def add(self, listener):
        self.listeners[ listener ] = 1

    def remove(self, listener):
        del self.listeners[ listener ]

    def post(self, event):
        print "post event %s" % event.name
        for listener in self.listeners.keys():
            listener.notify(event)

class Listener:
    def __init__(self, event_mgr=None):
        if event_mgr is not None:
            event_mgr.add(self) …
Run Code Online (Sandbox Code Playgroud)

python model-view-controller pygame duck-typing isinstance

7
推荐指数
1
解决办法
3784
查看次数

Python中是否存在isinstance(value,object)不是True的值?

我的理解是,由于类型/类统一,每个值都是源自的类型object.但是我在文档中找不到对此的绝对确认.尽管理所当然isinstance(anything, object)应该是True,但我也可以想象Python 2代码库中存在遗留边缘情况.有谁知道一个例子isinstance(value, object)不是 True

上下文:作为我正在设计的类型层次结构的一部分Alpha,我想要isinstance(obj, Alpha)总是返回一个全方位的类型True.我认为Python 2.6+ ABCMeta.register(object)应该可以解决这个问题,但我想确定一下.

编辑:为了后人的缘故,ABCMeta.register(object)将无法工作(尝试).Ethan Furman在下面的答案中提供了另一种解决方案.

python python-2.x isinstance

6
推荐指数
1
解决办法
389
查看次数

isinstance函数的奇怪行为

我有一个名为类Factor模块中Factor.py(https://github.com/pgmpy/pgmpy/blob/dev/pgmpy/factors/Factor.py),也有功能命名factor_productFactor.py为:

def factor_product(*args):
    if not all(isinstance(phi, Factor) for phi in args):
            raise TypeError("Input parameters must be factors")
    return functools.reduce(lambda phi1, phi2: _bivar_factor_operation(phi1, phi2,     
                                                            operation='M'), args)
Run Code Online (Sandbox Code Playgroud)

现在,如果我甚至将实例传递Factor给函数,它仍会抛出TypeError.来自调试器的几行,断点设置在if语句之上:

(Pdb) args
args = (<pgmpy.factors.Factor.Factor object at 0x7fed0faf76a0>, <pgmpy.factors.Factor.Factor object at 0x7fed0faf7da0>)

(Pdb) isinstance(args[0], Factor)
False

(Pdb) type(args[0])
<class 'pgmpy.factors.Factor.Factor'>

(Pdb) Factor
<class 'pgmpy.factors.Factor.Factor'>
Run Code Online (Sandbox Code Playgroud)

知道为什么会这样吗?

python isinstance python-3.x

6
推荐指数
1
解决办法
251
查看次数

Pytest 是类型的实例

我对 Python 很陌生,我正在设置一个小游戏,我想测试它。目前,我正在生成一个对象数组(石头、布、剪刀),每个对象都继承自 Roll 对象:

def build_the_three_rolls():
  return [Rock(), Paper(), Scissors()]
Run Code Online (Sandbox Code Playgroud)

这是我使用 py.test 进行的测试:

def test_building_rolls():
  assert len(build_the_three_rolls()) == 3
  assert isinstance(build_the_three_rolls()[0], Rock)
  assert isinstance(build_the_three_rolls()[1], Paper)
  assert isinstance(build_the_three_rolls()[2], Scissors)
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我收到以下错误:

>       assert isinstance(build_the_three_rolls()[1], Paper)
E       assert False
E        +  where False = isinstance(<roll.Paper object at 0x110ab42e8>, Paper)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会失败

谢谢!

更新:

这是 Roll 及其子类的定义:

class Roll:
def __init__(self, name, defeated_by_self, defeat_self):
    self.name = name
    self.defeated_by_self = defeated_by_self
    self.defeat_self = defeat_self


class Rock(Roll):
    def __init__(self):
        defeated_by_self = {}
        defeated_by_self["Scissors"] = "Scissors"
        defeat_self …
Run Code Online (Sandbox Code Playgroud)

python pytest isinstance python-3.x

6
推荐指数
1
解决办法
1万
查看次数

How to check a specific type of tuple or list?

Suppose,

var = ('x', 3)
Run Code Online (Sandbox Code Playgroud)

How to check if a variable is a tuple with only two elements, first being a type str and the other a type int in python? Can we do this using only one check? I want to avoid this -

if isinstance(var, tuple):
    if isinstance (var[0], str) and (var[1], int):
         return True
return False
Run Code Online (Sandbox Code Playgroud)

python types tuples isinstance

5
推荐指数
2
解决办法
3918
查看次数

检查numpy数组中的类型

我有不同类型的数据.他们中的大多数是int,有时float.它的int大小不同,因此8/16/32位是大小.
对于这种情况,我正在创建一个数字型转换器.因此我通过使用检查类型isinstence().这是因为我读过的isinstance()内容不如说type().

关键是我得到的很多数据都是numpy数组.我使用spyder作为IDE,然后我看到变量也是一个类型.但是当我输入isinstance(var,'type i read')我的时候False.

我做了一些检查:

a = 2.17 
b = 3 
c = np.array(np.random.rand(2, 8))
d = np.array([1])
Run Code Online (Sandbox Code Playgroud)

因为isinstance(var,type)我得到:

isinstance(a, float)
True
isinstance(b, int)
True
isinstance(c, float)  # or isinstance(c, np.float64)
False
isinstance(d, int)  # or isinstance(c, np.int32)
False
Run Code Online (Sandbox Code Playgroud)

c并且d是真实的,当我问

isinstance(c, np.ndarray)
True
isinstance(d, np.ndarray)
True
Run Code Online (Sandbox Code Playgroud)

我可以与在步骤检查ndarray

isinstance(c[i][j], np.float64)
True
isinstance(d[i], np.int32)
True
Run Code Online (Sandbox Code Playgroud)

但这意味着,对于每个维度,我必须添加一个新索引,否则它将False再次出现.我可以检查有型有 …

numpy isinstance python-3.x

5
推荐指数
3
解决办法
1万
查看次数

TypeError: isinstance() arg 2 必须是一个类型或类型的元组

如果你像我一样,你可能已经尝试过:

isinstance(my_var, [list, tuple])
Run Code Online (Sandbox Code Playgroud)

只得到:

TypeError: isinstance() arg 2 must be a type or tuple of types
Run Code Online (Sandbox Code Playgroud)

现在我完全理解了这个问题(错误信息很清楚)以及如何解决它。我也理解列表和元组之间的区别(可变与不可变)。

但是,我想了解的是 Python 解释器还允许将列表作为 isinstance arg 2 提供的权衡是什么?(无论如何,代码已经需要检查参数是标量还是元组)

如果你像我一样,它会节省很多不得不去应用修复的来回迭代,所以我很好奇是否有性能或其他原因让 Python 标准函数不混合接受列表和元组在这里?

python tuples immutability typeerror isinstance

5
推荐指数
0
解决办法
7084
查看次数

Python:检查两个变量之间相同类型的最佳方法

我正在检查 python 3.x 中两个变量是否具有相同的类型。做到这一点最理想的方法是什么?

举个例子:

class A():
    def __init__(self, x):
        self.x = x

class B(A):
    def __init__(self, x):
        x += 5
        super(B, self).__init__(x)
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想返回True两个类型为A和的变量B是否相互比较。以下是一些可能不起作用的解决方案:

>>> a = A(5)
>>> b = B(5)
>>>
>>> type(a) is type(b)
False
>>> isinstance(a, type(b))
False
>>> isinstance(b, type(a))
True
Run Code Online (Sandbox Code Playgroud)

最后一个并不理想,因为如中间示例所示,如果要检查的类型是变量类型的子类,False则返回。

我尝试过的唯一可以涵盖这里所有基础的解决方案是:

>>> isinstance(a, type(b)) or isinstance(b, type(a))
True
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

python types isinstance python-3.x

5
推荐指数
1
解决办法
3417
查看次数

Python 3:类型错误:下标泛型不能与类和实例检查一起使用

如何在 Python 2 和 Python 3 中测试子类型?

在 Python 2.7.18 中:

>>> import typing
>>> type_ = typing.List[str]
>>> issubclass(type_, typing.List)
True
Run Code Online (Sandbox Code Playgroud)

但在 Python 3.9.10 中,我得到:

TypeError: Subscripted generics cannot be used with class and instance checks

以下内容适用于我的情况,但它是一个黑客!最好在未来版本的 Python 中看到更强大的实现作为内置函数。

def _issubtype(type_, typeinfo):
    """
    Python 3 workaround for:
    TypeError: Subscripted generics cannot be used with class and instance checks

    Does not deal with typing.Union and probably numerous other corner cases.
    >>> _issubtype(typing.List[str], typing.List)
    True
    >>> _issubtype(typing.Dict[str, str], typing.List)
    False
    """ …
Run Code Online (Sandbox Code Playgroud)

typing subtype isinstance python-3.x subtyping

5
推荐指数
0
解决办法
3559
查看次数