1

我正在使用基于 GNU 操作系统的所有程序(Precise Puppy 5.4)

描述

  • 首先我创建一个类。
  • 在那个类里面我定义了一个方法
  • 此方法采用通用命名参数
  • 在里面我有一个if-elif-else与参数值一起使用的语句
  • if语句确定要返回的字符串

在类之外,我提示传递给变量的用户输入userinput

然后我用userinput作为参数调用该方法并将返回值分配给变量 name variable。然后我打印variable.

几点注意事项

首先,我知道还有其他方法可以达到相同的效果。我不使用其中之一的原因是因为我正在进行相当大的文本冒险,并且需要做出大量决策并分配大量变量。

如果我要使用类作为类别和方法作为特定区域来对游戏的不同部分(即:一个名为的类Player和名为statsinventory、等的方法)进行分类,那么使用代码会容易得多gold

class.function我知道该错误与我调用 时该类没有返回值的事实有关。但是该方法不在类内部调用,因此无法从类内部的方法返回值,而是在方法外部。

class classname () :
    def methodname (value) :
        if value == 1 :
            return "Hello World"
        else :
            return "Goodbye World!"
userinput = raw_input("Enter the number [1]\n")
variable = classname.methodname (userinput)
print (variable)

控制台输出

Enter the number [1]        (this is the prompt)
1                           (this is the user input)

(now the error)

Traceback (most recent call last):
    File "filename.py", line 8, in <module>
        variable = (classname.methodname (userinput))
TypeError: unbound method methodname() must be called with
classname instance as first argument (got classobj instance
instead)

这个问题已被解决。这个问题是一个简单的语法问题。这是解决方案的最大固定代码 Props 和用于格式化这篇文章的 Lev Levitsky!^.^

class classname () :
    def methodname (self, value) :
        if value == "1" :
            return "Hello World"
        else :
            return "Goodbye World!"
userinput = raw_input("Enter the number [1]\n")
variable = classname().methodname (userinput)
print (variable)
4

1 回答 1

3

你快到了。只需在@staticmethod前面添加def methodname(value);)

或者,如果您不打算使用静态方法,请尝试更改 methodname 的签名以接受一个额外的参数 self ( def methodname (self, value) :) 并确保始终methodname从实例调用:variable = (classname().methodname (userinput))

于 2013-01-19T22:17:40.953 回答