【问题标题】:TypeError: hola() takes 0 positional arguments but 1 was given [duplicate]TypeError:hola()采用0个位置参数,但给出了1个[重复]
【发布时间】:2018-12-29 20:43:27
【问题描述】:

这是一个简单的代码,我试图从同一个类中的另一个方法访问一个类中的一个方法,但它给了我这个错误任何帮助吗?

class menu:
    def __init__(self,a,b):
        self.a=a
        self.b=b

    def suma(self):
        x=self.a+self.b
        print(x)

    def hola(): 
        menu.suma()


menu=menu(1,2)
menu.hola()

【问题讨论】:

  • 你需要 def hola(self): ,你缺少自我......
  • def hola(): menu.suma()更改为def hola(self): self.suma()
  • 很好,对我有很大帮助,非常感谢您的帮助
  • @LeonardoRadilloescobar 标记为不正确的答案有效,但幸运的是,它不是正确的。

标签: python class methods typeerror


【解决方案1】:

How to avoid explicit 'self' in Python?

在 python 中你需要一个显式的 self。总是传入 self 参数。

class menu:
    def __init__(self,a,b):
        self.a=a
        self.b=b

    def suma(self):
        x=self.a+self.b
        print(x)

    def hola(self): 
        menu.suma()


menu=menu(1,2)
menu.hola()

【讨论】:

  • 你的代码有效吗?,你试过了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-16
  • 2013-10-28
  • 2020-05-20
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 2019-08-19
相关资源
最近更新 更多