tags:

views:

39

answers:

2

For code:

class a(object):
    a='aaa'
b=a()
print hasattr(a,'a')
print hasattr(b,'a')

who can be called by hasattr except 'class somebody'?

Thanks!

+1  A: 

You can call hasattr with any object as the first argument (and any string as the second argument): it just returns False if that object does not have an attribute by that name ("having" an attribute of course includes possibly inheriting or synthesizing it; hasattr(x,'y') is True if and only if accessing x.y would not raise an exception -- that's how it works internally: it tries getattr and catches the exception if any).

Alex Martelli
A: 

Accordingly to the Python documentation you must pass an object as parameter of the hasttr() function.

hasattr(object, name): The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)

Pedro Ghilardi