开发者

How can I conditionally only log something if it's a certain Class?

Something like this:

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__ == 'd开发者_Go百科jango.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


Classes are first class objects in Python:

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

Note: they're not strings, they're objects. Don't compare to "Foo" but to Foo


This should work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜