[英]Python isinstance(var, Type) always return False
I'm using Django with Python3. 我正在将Django与Python3配合使用。 There's a class defined in Model: 在Model中定义了一个类:
class PeopleAround(models.Model):
aaa_Id = models.ForeignKey(Board)
bbb = models.CharField(max_length=40)
ccc_Id = models.CharField(max_length=20)
ddd_Id = models.CharField(max_length=20)
in a view, I'm successfully retrieved some data by following: 在视图中,我通过以下操作成功检索了一些数据:
peopleAroundInDb = PeopleAround.objects.filter(aaa_Id=0).all()
and when do a testing, what surprised me is the expression below always return False: 当进行测试时,令我惊讶的是下面的表达式总是返回False:
isinstance(peopleAroundInDb[0], models.PeopleAround.__class__)
and also tested with equality for: 并同样测试了:
id(PeopleAround.__class__) and id(type(peopleAroundInDb[0]))
also NOT equal. 也不相等。
so anyone could help? 有人可以帮忙吗?
Don't use __class__
- as this returns a type object. 不要使用__class__
因为这会返回一个类型对象。
Just do this: 只要这样做:
isinstance(peopleAroundInDb[0], models.PeopleAround)
Example: 例:
>>> isinstance('text', str.__class__)
False
>>> isinstance('text', str)
True
Python doesn't need the class type object to compare, it wants to compare to the class itself. Python不需要类类型对象进行比较,它想与类本身进行比较。
EDIT: 编辑:
This technically works: 这在技术上是可行的:
>>> class test:
... def blah(self, thing):
... print(isinstance(thing, self.__class__))
... print(isinstance(thing, test))
...
>>> a = test()
>>> b = test()
>>> a.blah(b)
True
True
But I would say that it is clearer, and therefore a better idea, to use isinstance(thing, test)
over isinstance(thing, self.__class__)
但是我要说的是,使用isinstance(thing, test)
不是isinstance(thing, self.__class__)
更清晰,因此是一个更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.