3 ms·
Thing is, what does it mean for a property to "exist" in a dynamic language like Python? E.g. class P(object): def __getattr_(self, attrname):
by icebraining 11y ago
Thing is, what does it mean for a property to "exist" in a dynamic language like Python? E.g.
class P(object):
def __getattr_(self, attrname):
return "hello"
>>> p = P()
>>> print p.foo
hello
Does "p" have an attribute "foo"?
- alkonaut 11y agoThat is the snag isn't it. It's really difficult to provide any meaningful "reflection" without having proper static types. So in your example you could say "yes, because it gets a value when called" or "no, because it isn't explicitly declared". Since python is dynamic, the "hasattr" method really just means "does_invoking_this_attribute_return_something", which is very much not reflection. It would maybe be useful with getting only the explicitly defined attributes (say e.g. if you wanted to convert an object to an xsd schema). Your __getattr__ based attribute would not show up in that list obviously.