在Python中如何格式化用于方法的字符串?

2022-07-06 11:56:47 发布

您现在位置:Python中文网/ 问答频道 /正文

当试图运行listPersons()命令时,每个人/实例都应该调用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)

属性错误:

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'

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


Tags: 方法nameinself名称fornamesdeffilepersonattributeerrorsayhelloprintstrlistpersons
1条回答
网友
1楼 ·

出现此错误是因为names list是字符串列表,而不是您创建的people对象。因为您使用的是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))