【问题标题】:Calling methods that are nested inside classes调用嵌套在类中的方法
【发布时间】:2013-01-03 08:55:58
【问题描述】:

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

说明

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

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

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

一些注意事项

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

如果我要对不同的部分进行分类,使用代码会容易得多 使用 类作为类别,方法作为特定领域

我知道这个错误与我调用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)

这个问题已经解决了。这个问题是一个简单的语法问题。这是固定代码 为解决方案提供最大支持,为格式化这篇文章提供 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)

【问题讨论】:

  • 你的括号太多了;你可以解决几乎所有这些。
  • 它们让我更容易阅读。我知道我不需要他们
  • @MartijnPieters 那里,,,我修正了括号哈哈
  • @KonnerRasmussen ..或者可能不是。糟糕,我好像不小心覆盖了您的编辑,抱歉。
  • @LevLevitsky 不用担心...无论如何我更喜欢你的格式 =)

标签: python class python-2.7 typeerror


【解决方案1】:

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

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

【讨论】:

  • 应该用什么静态方法来解决问题?
  • 它使方法成为类方法而不是实例方法
  • 我认为静态方法是我想要的。我需要它,这样我就可以对代码进行排序,使其更加...分类,可以这么说
  • Konner Rasmussen,构造函数更“pythonic”的方式是将它们放在不同的包中;不要让它们成为静态方法。
  • 我认为你应该阅读关于包和模块的官方文档:docs.python.org/2/tutorial/modules.html。它很好地解释了这些概念。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多