Check if object attribute name appears in a string python
<p>I want to:</p>

<ul>
<li>check whether a string contains an object property</li>
<li>if it does then access the attribute</li>
</ul>

<p>So for an object of class </p>

<pre><code>class Person(object):
    name = ""
    age = 0
    major = ""

    def __init__(self, name="", surname="", father="", age =0):
        self.name = name
        self.surname = surname
        self.father = father
        self.age = age
        self.identity = name +" "+ surname
    def __str__(self):
        return self.identity

    __repr__ = __str__
</code></pre>

<p>and object</p>

<pre><code>person = Person("Earl", "Martin", "Jason", 40)
</code></pre>

<p>I would like for string "What is the name"
to return person.name 
(I already know which object the string is about)</p>

<p>The most basic solution would be to do cases for each property being there but the actual code has quite a few and I am sure I don't manually have to write them out, I am just new to programming so I am not sure what syntax is used for this</p>

<p>Any help appreciated </p>

<p>You are looking for the function <code>hasattr()</code> and <code>getattr()</code>.</p>

<p>To check whether the attribute exists:</p>

<pre><code>hasattr(Person(), 'string')
</code></pre>

<p>And to call the attribute:</p>

<pre><code>getattr(Person(), 'string')
</code></pre>

python string python-2.7 class object