hasattr documentation says that it takes an object and an attribute name and lets you know if that attribute exists on that object.
I have discovered that it seems to work on class names too (i.e. not an instance object).
Something like:
class A:
def Attr1(self):
pass
> hasattr(A, 'Attr1')
True
>
I would like to use this to make some test code easier to write, but don't want to be bitten later in case this is a side effect of the implementation and not really intended.
Please don't ask to see the test code to see if I can do something else, as that is not really the question.
Is there any official python stance on this? I presume the object referred to, in the documentation is talking about an instance object.
I tried googling (and looking at some questions in StackOverflow), but didn't seem to find anything.
instance.method(stuff ...)
is in fact syntactic sugar forClass.method(instance, stuff ...)
, i.e. those methods are in fact attributes of the class. – Tennesseehasattr
on anything. – Precontracthasattr(A, blah)
, instead ofhasattr(x, blah)
wherex = A()
. – Pepintype
(or whatever the metaclass of the class is). – Amidst5
is anint
object.int
is atype
object. Functions, classes, modules; all are objects of various kinds. Python is wholly object-oriented, it doesn't have the "primitive" data types of e.g. Java. – Precontract