On 14/10/12 05:29, Matthew Ngaha wrote:
im trying to understand this hasattr function. i am supposed to pass in an
object and an attribute name into its parametres... so im trying to get it
to return True. Here's a quick test

class Test:
     def __init__(self):
        self.att = "testing"


Okay, so you have a class that defines an attribute named "att".

e = Test()
hasattr(e, e.att)
False

Break this down step by step. First you create an instance, "e", with an
attribute e.att. Python evaluates e.att to get the string "testing", then
looks up hasattr(e, "testing"). Does e have an attribute called "testing"?
No. So it returns False.


hasattr(e, "testing")
False

Same here, except that you bypass the evaluation of e.att and enter the
string "testing" manually.

What you need to pass to hasattr (as well as its friends getattr and
setattr) is the *name* of the attribute, not its contents:


hasattr(e, "att")

will return True.



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to