我的代码:
#!/usr/bin/python
class FirstClass():
def setdata(self,value):
self.data=value
def getname(self,name):
self.data=name
def display(self):
print self.data
x = FirstClass( )
y = FirstClass( )
x.setdata("King Arthur")
x.getname("dnj")
x.display()
class SecondClass(FirstClass):
def display(self):
print 'Current value = "%s"' % self.data
z = SecondClass()
z.setdata(42)
z.display()
class ThirdClass(FirstClass):
def display(self):
print 'Her name is = "%s"' % self.data
p = ThirdClass()
p.getname(dunja)
p.display()
当我运行它时,我得到了这个:
dnj
Current value = "42"
Traceback (most recent call last):
File "pr54.py", line 31, in <module>
p.getname(dunja)
NameError: name 'dunja' is not defined
我应该创建其他显示功能还是......?我不明白为什么它不起作用,因为层次结构是一样的。
答案 0 :(得分:2)
dunja
被视为变量。要将其视为字符串,请将其作为
p = ThirdClass()
p.getname("dunja")
p.display()