How do I format a string to use for a Method in Python?
<p>When trying to run the listPersons() command, every Person/Instance should call the sayHello() method. But as the names are str, it would raise an AttributeError (see below).</p>

<p>How do I format the names so I can use the methods on them?</p>

<pre><code>class person:
    def __init__ (self, name):
        self.name = name
    def sayHello(self):
        print("Hello World, I'm", self.name)

def listPersons():
    print ("There are", len(names), "persons here, please everybody say hello to the world!")

    for name in names:
        print(name.sayHello())

names = ["Tobias", "Lukas", "Alex", "Hannah"]

for name in names:
    globals()[name]  = person(name)
</code></pre>

<p>AttributeError:</p>

<pre><code>Traceback (most recent call last):
File "&lt;pyshell#97&gt;", line 1, in &lt;module&gt;
listPersons()
File "/Users/user/Desktop/test.py", line 12, in listPersons
print(name.sayHello())
AttributeError: 'str' object has no attribute 'sayHello'
</code></pre>

<p>Thank you so much for your help! :-)</p>

<p>You're getting this error because names list is a list of strings, not the people objects you create. Since you are using globals(), each person is being assigned to a variable in the global scope. Rather than using globals(), I would suggest having a list of people. </p>

<p>Another problem you will run into is that you are trying to print the output of person.sayHello, but that does not return anything. You could just call the function instead. </p>

<p>Both of these changes together:</p>

<pre><code>class person:
    def __init__ (self, name):
        self.name = name
    def sayHello(self):
        print("Hello World, I'm", self.name)

def listPersons():
    print ("There are", len(people), "persons here, please everybody say hello to the world!")

    for name in people:
        name.sayHello()

names = ["Tobias", "Lukas", "Alex", "Hannah"]
people = []

for name in names:
    people.append(person(name))
</code></pre>

python methods format