“TypeError:method()需要1个位置参数,但给出了2个”但我只传递了一个

问题描述 投票:0回答:12

如果我有课...

class MyClass:

    def method(arg):
        print(arg)

...我用它来创建一个对象...

my_object = MyClass()

...我称之为

method("foo")
,就像这样...

>>> my_object.method("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)

...为什么 Python 告诉我我给了它两个参数,而我只给出了一个?

python methods arguments self
12个回答
616
投票

在Python中,这个:

my_object.method("foo")

...是语法糖,解释器在幕后将其翻译为:

MyClass.method(my_object, "foo")

...正如您所看到的,它确实有两个参数 - 只是从调用者的角度来看,第一个参数是隐式的。

这是因为大多数方法都会对它们所调用的对象进行一些操作,因此需要有某种方式在方法内部引用该对象。按照惯例,第一个参数在方法定义中称为

self

class MyNewClass:

    def method(self, arg):
        print(self)
        print(arg)

如果您在

method("foo")
的实例上调用
MyNewClass
,它会按预期工作:

>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo

偶尔(但不经常),您真的关心您的方法绑定到的对象,在这种情况下,您可以使用内置的 staticmethod()

 函数来
装饰该方法来这么说:

class MyOtherClass:

    @staticmethod
    def method(arg):
        print(arg)

...在这种情况下,您不需要在方法定义中添加

self
参数,它仍然有效:

>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo

44
投票

简单来说

在 Python 中,您应该将

self
添加为类中所有已定义方法的第一个参数:

class MyClass:
  def method(self, arg):
    print(arg)

然后你就可以根据你的直觉使用你的方法了:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

为了更好地理解,您还可以阅读这个问题的答案:自我的目的是什么?


25
投票

遇到此类错误时需要考虑的其他事项:

我遇到了这个错误消息,发现这篇文章很有帮助。事实证明,在我的例子中,我覆盖了存在对象继承的

__init__()

继承的示例相当长,所以我将跳到一个不使用继承的更简单的示例:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

结果是:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm 没有发现这个拼写错误。 Notepad++ 也没有(其他编辑器/IDE 可能)。

当然,这是一个“不带参数”类型错误,就 Python 中的对象初始化而言,它与期望一个时的“有两个”没有太大区别。

解决主题:如果语法正确,将使用重载初始值设定项,但如果不正确,它将被忽略并使用内置的。该对象不会期望/处理这个并且抛出错误。

如果出现语法错误:修复很简单,只需编辑自定义 init 语句即可:

def __init__(self, name):
    self.name = name

21
投票

此问题也可能是由于未能正确将关键字参数传递给函数而导致的。

例如,给定一个定义如下的方法:

def create_properties_frame(self, parent, **kwargs):

这样的电话:

self.create_properties_frame(frame, kw_gsp)

会导致

TypeError: create_properties_frame() takes 2 positional arguments but 3 were given
,因为
kw_gsp
字典被视为位置参数,而不是被解包到单独的关键字参数中。

解决方案是在参数中添加

**

self.create_properties_frame(frame, **kw_gsp)

15
投票

正如其他答案中提到的 - 当您使用实例方法时,您需要传递

self
作为第一个参数 - 这是错误的根源。

除此之外,重要的是要了解只有实例方法才将

self
作为第一个参数才能引用实例

如果方法是 Static,您不会传递

self
,而是传递
cls
参数(或
class_
)。

请参阅下面的示例。

class City:

   country = "USA" # This is a class level attribute which will be shared across all instances  (and not created PER instance)

   def __init__(self, name, location, population):
       self.name       = name
       self.location   = location
       self.population = population
 
   # This is an instance method which takes self as the first argument to refer to the instance 
   def print_population(self, some_nice_sentence_prefix):
       print(some_nice_sentence_prefix +" In " +self.name + " lives " +self.population + " people!")

   # This is a static (class) method which is marked with the @classmethod attribute
   # All class methods must take a class argument as first param. The convention is to name is "cls" but class_ is also ok
   @classmethod
   def change_country(cls, new_country):
       cls.country = new_country

一些测试只是为了让事情更清楚:

# Populate objects
city1 = City("New York",    "East", "18,804,000")
city2 = City("Los Angeles", "West", "10,118,800")

#1) Use the instance method: No need to pass "self" - it is passed as the city1 instance
city1.print_population("Did You Know?") # Prints: Did You Know? In New York lives 18,804,000 people!

#2.A) Use the static method in the object
city2.change_country("Canada")

#2.B) Will be reflected in all objects
print("city1.country=",city1.country) # Prints Canada
print("city2.country=",city2.country) # Prints Canada

9
投票

当您未指定

__init__()
或任何其他正在寻找的方法的参数时,就会发生这种情况。

例如:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj = Dog("JIMMY", 1, 2, 3, "WOOF")

当你运行上面的程序时,它会给你一个这样的错误:

TypeError: __init__() takes 1 positional argument but 6 were given

我们怎样才能摆脱这个东西?

传参数就可以了,找什么

__init__()
方法

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

6
投票

如果想在不创建对象的情况下调用方法,可以将方法改为静态方法。

class MyClass:

    @staticmethod
    def method(arg):
        print(arg)

MyClass.method("i am a static method")

5
投票

当我睡眠不足时,我会收到此错误,并使用

def
而不是
class
创建一个类:

def MyClass():
    def __init__(self, x):
        self.x = x

a = MyClass(3)
-> TypeError: MyClass() takes 0 positional arguments but 1 was given

0
投票

如果您在 Django 中遇到过这种情况,那么这就是它的含义:

  1. 向函数添加一个对象,Django会理解其余的,例如
def display_genre(self, obj):
        return ', '.join(genre.name for genre in obj.genre.all())}


0
投票

如果函数采用一个位置参数和任何其他变量作为关键字参数,您也可能会收到相同的错误消息。要解决此问题,请将附加变量作为关键字参数传递。

触发错误的示例:

def func(value, **kwargs):
    pass

func(1, 2)   # <--- TypeError: func() takes 1 positional argument but 2 were given

func(1, b=2) # <--- OK

另一个更实际的例子:django 的

authenticate()
方法可用于验证用户名和密码等凭据,但它将它们作为关键字参数(docs源代码),因此出现以下场景:

from django.contrib.auth import authenticate
authenticate(username, password)                    # <--- TypeError
authenticate(username=username, password=password)  # <--- OK

-1
投票

就我而言,我忘记添加

()

我是这样调用方法的

obj = className.myMethod

但应该是这样的

obj = className.myMethod()

-1
投票

你实际上应该创建一个类:

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
        return self.acc
© www.soinside.com 2019 - 2024. All rights reserved.