列表中的对象

2024-10-04 11:32:11 发布

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

我有一个带方法的类。现在,我把这个类放在一个列表中。 当我试图打印一个方法时,我会:

print(listname[pointer].method)

但是当我编译时,它说对象不支持索引

确切的代码如下:

class hero():
    def __init__(self, heroname):
        self.h=heroname

herolist=[]
herolist.append(hero)

print(herolist[0].h)

我希望代码会打印出英雄的名字,但事实并非如此。我做错什么了

编辑:

抱歉,我忘了在代码中显示它,但在类之外,我确实实例化了我试图调用的对象。确切地说,我做了如下的事情:

heroone=hero()
heroone.h='jude'

Tags: 对象方法代码self列表methodclassprint
3条回答

你有一些问题。首先,初始化方法的名称是__init__每边有两个下划线),而不是___init___。其次,通过附加hero,您就是在附加类本身。类本身没有h属性。只有它的实例才会有h属性,因为只有在创建实例时才会调用__init__。第三,您忘记了self方法中的__init__参数。第四,您显然编写了__init__,希望得到一个“heroname”参数,但是您没有传递任何这样的参数(您不传递任何参数,因为您从未实例化该类。)

试试这个:

class hero():
    def __init__(self, heroname):
        self.h = heroname

herolist=[]
herolist.append(hero('Bob the Hero'))

print(herolist[0].h)

您正在使用three_withinit方法,因为没有调用哪个构造函数。 两边都需要两个_。 要将名称赋给h,请将其传递给init方法。 使用CamelCase命名类

以下是工作代码:

class Hero():
    def __init__(self, heroname):
        self.h = heroname

herolist=[]

herolist.append(Hero('Dude'))

print(herolist[0].h)

存储的是类定义,而不是实例对象,这意味着heroname没有值。你可以写:

herolist.append(hero('Achile'))

你的例子会像预期的那样起作用

相关问题 更多 >