如果它是某个类,我怎么能有条件地只记录某些东西?

时间:2010-04-14 21:18:03

标签: python django

这样的事情:

if self.__class__ == "User":
                logging.debug("%s non_pks were found" %  (str(len(non_pks))) )

In [2]: user = User.objects.get(pk=1)

In [3]: user.__class__
Out[3]: <class 'django.contrib.auth.models.User'>

In [4]: if user.__class__ == 'django.contrib.auth.models.User': print "yes"
   ...: 

In [5]: user.__class__ == 'django.contrib.auth.models.User'
Out[5]: False

In [6]: user.__class__ == 'User'
Out[6]: False

In [7]: user.__class__ == "<class 'django.contrib.auth.models.User'>"
Out[7]: False

2 个答案:

答案 0 :(得分:3)

类是Python中的第一类对象:

>>> class Foo(object):
...     pass
... 
>>> a = Foo()
>>> a.__class__ == Foo
True

注意:它们不是字符串,它们是对象。不要与"Foo"进行比较,而应与Foo

进行比较

答案 1 :(得分:2)

这应该有效:

if user.__class__.__name__ == 'User':