有人建议我把这个重新贴出来以便更清楚。
上完一节课,剩下的就不上这节课了。欢迎任何指导。我已经得出了这个问题的一部分,在那里我坚持要保持简短。我还附上了我的工作。
在下面的工作中,我希望能够创建一个包含一个变量的类。我希望能够更改该变量并打印新变量。例如,将值从horns=2更改为horns=4。这个问题特别要求我使用下面的3个函数来回答这个问题。使用当前代码,在raw_输入提示下输入值后,会收到一条错误消息。
提前谢谢你的帮助。
问题如下:
创建一个包含1个变量的类,该类包含自己的属性。提供以下3种方法:
getvariable1()-使用返回键返回属性1的值
setvariable1()-这应该允许为属性1指定新值-接受输入所需的其他参数。
printerfun()-打印对象变量的值。
创建自己的类对象,并为创建的对象调用get&set方法。使用printerfun()方法检查代码是否有效。
我的工作:
class animal:
horns = 2
def printerfun(self):
print getHorns()
def getHorns(self): #don't get where I should call this
return self.horns
def setHorns(horns):
self.horns = horns
animal_1 = animal()
F1 = raw_input('Please enter number of horns: ')
setHorns(F1)
setHorns
不存在:animal.setHorns
存在。 是一个class method似乎你需要读一点Object Oriented Programming的知识,这是当涉及到类时使用的编程风格。
在这个特定的练习中,您需要创建一个
animal
object。为此,您需要instanciate类。这就是你用animal_1 = animal()
做的。animal_1
现在是animal
类的对象,您可以调用它的方法:animal_1.setHorns(2)
如果您仍然在与这些概念作斗争,您可能需要阅读更多的ground to earth tutorial in python
这是你想要的吗?
这将输出:
相关问题 更多 >
编程相关推荐