Python-创建类并使用函数更改其对象值

2024-09-25 00:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

有人建议我把这个重新贴出来以便更清楚。

上完一节课,剩下的就不上这节课了。欢迎任何指导。我已经得出了这个问题的一部分,在那里我坚持要保持简短。我还附上了我的工作。

在下面的工作中,我希望能够创建一个包含一个变量的类。我希望能够更改该变量并打印新变量。例如,将值从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) 

Tags: 对象方法代码selfgetraw属性def
2条回答

setHorns不存在:animal.setHorns存在。 是一个class method

似乎你需要读一点Object Oriented Programming的知识,这是当涉及到类时使用的编程风格。

在这个特定的练习中,您需要创建一个animalobject。为此,您需要instanciate类。这就是你用animal_1 = animal()做的。animal_1现在是animal类的对象,您可以调用它的方法:animal_1.setHorns(2)

如果您仍然在与这些概念作斗争,您可能需要阅读更多的ground to earth tutorial in python

这是你想要的吗?

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

相关问题 更多 >