我有一个带方法的类。现在,我把这个类放在一个列表中。 当我试图打印一个方法时,我会:
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'
你有一些问题。首先,初始化方法的名称是
__init__
(每边有两个下划线),而不是___init___
。其次,通过附加hero
,您就是在附加类本身。类本身没有h
属性。只有它的实例才会有h
属性,因为只有在创建实例时才会调用__init__
。第三,您忘记了self
方法中的__init__
参数。第四,您显然编写了__init__
,希望得到一个“heroname”参数,但是您没有传递任何这样的参数(您不传递任何参数,因为您从未实例化该类。)试试这个:
您正在使用three
_
withinit
方法,因为没有调用哪个构造函数。 两边都需要两个_
。 要将名称赋给h
,请将其传递给init方法。 使用CamelCase命名类以下是工作代码:
存储的是类定义,而不是实例对象,这意味着
heroname
没有值。你可以写:你的例子会像预期的那样起作用
相关问题 更多 >
编程相关推荐