Why don't objects have hasattr and getattr as attributes?
<p>When you need to access an object's attributes dynamically in Python, you can just use the builtin functions <code>hasattr(object, attribute)</code> or <code>getattr(object, attribute)</code>.</p>

<p>However this seems like an odd order for the syntax to take. It's less readable and intuitive as it messes up the regular sentence structure for English.</p>

<blockquote>
  <p><code>if hasattr(person, age):</code><br>
  if has attribute Person age</p>
</blockquote>

<p>Where having it as a method of the object would be much more readable:</p>

<blockquote>
  <p><code>if person.hasattr(age):</code><br>
  if Person has attribute age</p>
</blockquote>

<p>Is there a particular reason for not implementing it this way? I could imagine there are cases where you're not sure if the object is even a proper object, rather than just <code>None</code>, but surely in those cases of uncertainty you could just use the builtin function anyway for extra safety.</p>

<p>Is there some other drawback or consideration I'm not thinking of that makes adding these not worth it?</p>

<p>You'll find quite a few similar examples - like <code>len(obj)</code> instead of <code>obj.length()</code>, <code>hash(obj)</code> instead of <code>obj.hash()</code>, <code>isinstance(obj, cls)</code> instead of <code>obj.isinstance(cls)</code>. You may also have noticed that addition is spelled <code>obj1 + obj2</code> instead of <code>obj1.add(obj2)</code>, substraction spelled <code>obj1 - obj2</code> instead of <code>obj1.sub(obj2)</code> etc...  The point is that some builtin "functions" are to be considered as operators rather than really functions, and are supported by "__magic__" methods (<code>__len__</code>, <code>__hash__</code>, <code>__add__</code> etc). </p>

<p>As of the "why", you'd have to ask GvR but historical reasons set asides, it at least avoids a lot of namespace pollution / name clashes. How would you name the length of a "Line" or "Rectangle" class if <code>length</code> was already a "kind of but not explicitely reserved" name ? And how should introspection understand that <code>Rectangle.length()</code> doesn't mean <code>Rectangle</code> is a sizeable sequence-like object ?</p>

<p>Using generic "operator" functions (note that proper operators also exist as functions, cf the <code>operator</code> module) + "__magic__" methods make the intention clear and leaves normal names open for "user space" semantic.</p>

<p>wrt/ the "regular sentence structure for English", I have to say I don</p>

<blockquote>
  <p>I could imagine there are cases where you're not sure if the object is
  even a proper object, rather than just None</p>
</blockquote>

<p><code>None</code> <em>is</em> a "proper" object. Everything in Python (well, everything you can bind to a name) is a "proper" object. </p>

python class