how can i know if a python object have a attribute such as 'attr1'?

T

thinke365

for example, i may define a python class:
class A:
def sayHello():
print 'hello'

a = A()
a.attr1 = 'hello'
a.attr2 = 'bb'

b = A()
a.attr2 = 'aa'

how can i know whether an object have an attribute named attr1?
 
A

Arnaud Delobelle

thinke365 said:
for example, i may define a python class:
class A:
def sayHello():
print 'hello'

a = A()
a.attr1 = 'hello'
a.attr2 = 'bb'

b = A()
a.attr2 = 'aa'

how can i know whether an object have an attribute named attr1?

hasattr(a, 'attr1')
 
J

Jan Kaliszewski

or
try: a.attr1
except AttributeError: pass

or

-- if you are interested only in attributes contained by attributes dict
of this particular object (and no in attributes of its type, base types
nor attributes calculated on-demand by __getattr__/__getattribute__
methods) --

you can check its __dict__ --
* using vars(), e.g.: if 'attr1' in vars(a)...
* or directly (less elegant?), e.g.: if 'attr1' in a.__dict__...

But please remember that it doesn't work for instances of types with
__slots__ defined (see:
http://docs.python.org/reference/datamodel.html#slots).

Regards,
*j
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top