How do I format a string to use for a Method in Python? -


when trying run listpersons() command, every person/instance should call sayhello() method. names str, raise attributeerror (see below).

how format names can use methods on them?

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 hello world!")      name in names:         print(name.sayhello())  names = ["tobias", "lukas", "alex", "hannah"]  name in names:     globals()[name]  = person(name) 

attributeerror:

traceback (most recent call last): file "<pyshell#97>", line 1, in <module> listpersons() file "/users/user/desktop/test.py", line 12, in listpersons print(name.sayhello()) attributeerror: 'str' object has no attribute 'sayhello' 

thank help! :-)

you're getting error because names list list of strings, not people objects create. since using globals(), each person being assigned variable in global scope. rather using globals(), suggest having list of people.

another problem run trying print output of person.sayhello, not return anything. call function instead.

both of these changes together:

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 hello world!")      name in people:         name.sayhello()  names = ["tobias", "lukas", "alex", "hannah"] people = []  name in names:     people.append(person(name)) 

Comments