Class 实例化向函数添加额外的参数

Class instantiation adding extra arguments to function

我有一个 python3 class,代码如下

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')

然后mooreturns错误

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

我想这与接受任何 __init__ 作为参数的函数有关,但我不确定如何解决这个问题。

感谢您的帮助!

在为 python 中的 class 定义方法时,您需要将 self 作为传递到定义中的第一个参数。见下文:

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

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

如果您正在定义一个函数但不传递任何参数,您仍将其定义为:

def foo(self):
  # do stuff