Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

0 views
Skip to first unread message

thinke365

unread,
Jan 23, 2010, 10:49:46 AM1/23/10
to pytho...@python.org

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?

--
View this message in context: http://old.nabble.com/how-can-i-know-if-a-python-object-have-a-attribute-such-as-%27attr1%27--tp27286937p27286937.html
Sent from the Python - python-list mailing list archive at Nabble.com.

Arnaud Delobelle

unread,
Jan 23, 2010, 10:56:29 AM1/23/10
to
thinke365 <thin...@gmail.com> writes:

> 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')

--
Arnaud

Terry Reedy

unread,
Jan 23, 2010, 6:38:29 PM1/23/10
to pytho...@python.org

or
try: a.attr1
except AttributeError: pass

Terry Jan Reedy


Jan Kaliszewski

unread,
Jan 25, 2010, 3:57:48 PM1/25/10
to pytho...@python.org
24-01-2010, 00:38:29 Terry Reedy <tjr...@udel.edu> wrote:

> On 1/23/2010 10:56 AM, Arnaud Delobelle wrote:

> 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

--
Jan Kaliszewski (zuo) <z...@chopin.edu.pl>

0 new messages