How can I test to see if a class contains a particular attribute?
Posted
by BryanWheelock
on Stack Overflow
See other posts from Stack Overflow
or by BryanWheelock
Published on 2010-04-25T15:42:49Z
Indexed on
2010/04/25
16:03 UTC
Read the original article
Hit count: 446
How can I test to see if a class contains a particular attribute?
In [14]: user = User.objects.get(pk=2)
In [18]: user.__dict__
Out[18]:
{'date_joined': datetime.datetime(2010, 3, 17, 15, 20, 45),
'email': u'[email protected]',
'first_name': u'',
'id': 2L,
'is_active': 1,
'is_staff': 0,
'is_superuser': 0,
'last_login': datetime.datetime(2010, 3, 17, 16, 15, 35),
'last_name': u'',
'password': u'sha1$44a2055f5',
'username': u'DickCheney'}
In [25]: hasattr(user, 'username')
Out[25]: True
In [26]: hasattr(User, 'username')
Out[26]: False
I'm having a weird bug where more attributes are showing up than I actually define. I want to conditionally stop this.
e.g.
if not hasattr(User, 'karma'):
User.add_to_class('karma', models.PositiveIntegerField(default=1))
© Stack Overflow or respective owner