如何格式化用于Python中的Method的字符串?

时间:2016-09-01 23:54:11

标签: python methods format

尝试运行listPersons()命令时,每个Person / Instance都应该调用sayHello()方法。但是由于名称是str,它会引发AttributeError(见下文)。

如何格式化名称以便我可以使用它们的方法?

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)

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'

非常感谢你的帮助! : - )

1 个答案:

答案 0 :(得分:2)

您收到此错误,因为名称列表是字符串列表,而不是您创建的人物对象。由于您使用的是globals(),因此每个人都被分配到全局范围内的变量。而不是使用globals(),我建议有一个人的列表。

您将遇到的另一个问题是您正在尝试打印person.sayHello的输出,但这不会返回任何内容。你可以改为调用函数。

这两个变化在一起:

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))