【问题标题】:Class instantiation adding extra arguments to function类实例化向函数添加额外参数
【发布时间】:2021-09-17 13:47:16
【问题描述】:

我有一个带有以下代码的 python3 类

class Cow:

    def __init__(self, *bovines):
        for i in bovines:
            self.i = i
            print(i)

    def moo(a,b):
        print(a)

animal = Cow
animal.moo('a','b')

它正确打印a

但是,如果我运行以下命令(唯一的区别是 animal = Cow('Annie') 而不是 animal = Cow

class Cow:

    def __init__(self, *bovines):
        for i in bovines:
            self.i = i
            print(i)

    def moo(a,b):
        print(a)

animal = Cow('Annie')
animal.moo('a','b')

然后moo返回错误

TypeError: moo() takes 2 positional arguments but 3 were given

我想这与函数接受 __init__'d 作为参数有关,但我不知道如何解决这个问题。

感谢您的帮助!

【问题讨论】:

  • “我想这与函数接受 __init__'d 作为参数有关”请注意您发布的代码如何包含名为__init__?它被命名为__init。这大概是问题的原因 - 尽管您发布的使用示例没有任何意义:“用cow 实例化animal”已经没有意义,并且您再次显示相同的代码块指出导致问题的不同做法。
  • 以后,请不要依赖诸如“具有类似这样的结构”之类的模糊描述,而是创建一个minimal, reproducible example
  • 谢谢。这是格式错误。代码块现在不一样了。我认为现在这是最小且可重复的。我还固定了大小写。
  • 我现在正在修。
  • 你的“唯一”区别是一个巨大的区别。 animal = Cow 根本不创建 Cow 的实例;它只是使animal 成为对该类的另一个引用。

标签: python python-3.x class oop arguments


【解决方案1】:

在python中为类定义方法时,需要将self作为第一个参数传入定义。见下文:

def moo(self, a, b):
    print(a)

类型错误是因为你传入了 self ,然后是你想通过调用函数 moo 传入的参数 (a & b)。因此“TypeError: moo() 接受 2 个位置参数,但给出了 3 个”。

如果你定义了一个函数但没有传入任何参数,你仍然可以将它定义为:

def foo(self):
  # do stuff

【讨论】:

  • 谢谢!这是问题所在,现在解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 2011-12-01
  • 2012-10-25
  • 1970-01-01
相关资源
最近更新 更多