Check if method already is in instance in object?
<p>I'm trying to see whether an instance of an attribute already exists for my object. As you can see below, I want to do something if my <code>Dog</code> object has a certain attribute, via the <code>do_something_if_has_aged</code> method. How can I check whether a certain attribute has already been declared? Usually you would check for existence with something like this, which returns <code>False</code>:</p>

<pre><code>obj = None
if obj:
    print(True)
else:
    print(False)
</code></pre>

<p>Here's my minimum reproducible example:</p>

<pre><code>&gt;&gt;&gt; class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def add_years(self, years):
        self.age += years
        self.has_aged = True
    def do_something_if_has_aged(self):
        if self.has_aged:
            print("The dog has aged and is %d years closer to death" % self.years)
        else:
            print("The dog hasn't aged, apparently.")


&gt;&gt;&gt; dog = Dog('Spot', 3)
&gt;&gt;&gt; dog.age
3
&gt;&gt;&gt; dog.do_something_if_has_aged()
Traceback (most recent call last):
  File "&lt;pyshell#193&gt;", line 1, in &lt;module&gt;
    dog.do_something_if_has_aged()
  File "&lt;pyshell#190&gt;", line 9, in do_something_if_has_aged
    if not self.has_aged:
AttributeError: 'Dog' object has no attribute 'has_aged'
&gt;&gt;&gt; dog.add_years(1)
&gt;&gt;&gt; dog.age
4
&gt;&gt;&gt; dog.do_something_if_has_aged()
The dog hasn't aged, apparently.
</code></pre>

<p>Clearly the dog <em>has aged</em>, though.</p>

<p>I apologize if the title doesn't reflect what I'm trying to convey below; I'm new to OOP.</p>

<p>I would rewrite the <code>__init__</code> method to include <code>self.has_aged = False</code> to avoid having to do inspection:</p>

<pre><code>class Dog(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.has_aged = False # Starting value so it is guaranteed to be defined (unless explicitly deleted).
</code></pre>

<p>Now, the rest of your class should work as written. However, if you want to see if an attribute has been defined on an object, you can write this:</p>

<pre><code>class Foo(object):
    def set_bar(self):
        self.bar = True # Define the attribute bar if it is not yet defined.

    def is_bar_set(self):
        return hasattr(self, 'bar')
</code></pre>

python class oop attributes instance