gpt4 book ai didi

Python - 创建一个类并使用函数更改它的对象值

转载 作者:行者123 更新时间:2023-11-28 18:49:53 24 4
gpt4 key购买 nike

我被建议重新发布这个以便更清楚。

上了一节课,剩下的就少了这节课。任何指导表示赞赏。我已经得出了问题的一部分,以保持简短。我也附上了我的工作。

通过下面的工作,我希望能够创建一个包含一个变量的类。我希望能够更改该变量并打印新变量。例如,将值从horns = 2更改为horns = 4。问题要求我具体使用下面的3个函数来回答问题。使用我当前的代码,我在 raw_input 提示符下输入值后收到一条错误消息。

在此先感谢您的帮助。

问题如下:

创建一个包含 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)

最佳答案

这是你想要得到的吗?

class animal: 
horns = 2

def printerfun(self):
print self.getHorns()

def getHorns(self):
return self.horns

def setHorns(self, horns):
self.horns = horns

if __name__ == "__main__"
animal_1 = animal()
animal_1.printerfun()

F1 = raw_input('Please enter number of horns: ')
animal_1.setHorns(F1)
animal_1.printerfun()
horns = animal_1.getHorns()
print(horns)

这个输出:

>>> 2
>>> Please enter number of horns: 4
>>> 4
>>> 4

关于Python - 创建一个类并使用函数更改它的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14613250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com