我将通过以下printIt()
方法打印列表中的元素。对于for循环的最后一次迭代,我需要一个强制转换来将索引类型s
更改为我自己的类类型ord
,以便可以使用printIt()
方法。
有人对此案有任何想法吗?
谢谢
class ord:
def __init__(self, aString):
self = aString
def printIt(self):
print(self.text)
s1 = ord("a")
s2 = ord("b")
note = [s1, s2]
for s in note:
s.printIt() # something like s(type(ord), ord) which does not work!!!
已编辑:以下是生成的错误:
'int' object has no attribute 'printIt'
答案 0 :(得分:1)
将你的课程重命名为其他内容... ord是一个内置的,你无意中影子......
class ordX:
def __init__(self, aString):
self.text = aString
def printIt(self):
print(self.text)
s1 = ordX("a")
s2 = ordX("b")
note = [s1, s2]
for s in note:
s.printIt()
但你还应该为它定义str和repr
class ordX:
def __init__(self, aString):
self.text = aString
def __str__(self):
return self.text
def __repr__(self):
return "<OrdX '%s'>"%self
s1 = ordX("a")
s2 = ordX("b")
note = [s1, s2]
for s in note:
print(s)
print(repr(s))