Missing 1 required positional argument self python ошибка

I got the same error below:

TypeError: test() missing 1 required positional argument: ‘self’

When an instance method had self, then I called it directly by class name as shown below:

class Person:
    def test(self): # <- With "self" 
        print("Test")

Person.test() # Here

And, when a static method had self, then I called it by object or directly by class name as shown below:

class Person:
    @staticmethod
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

So, I called the instance method with object as shown below:

class Person:
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

And, I removed self from the static method as shown below:

class Person:
    @staticmethod
    def test(): # <- "self" removed 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

Then, the error was solved:

Test

In detail, I explain about instance method in my answer for What is an «instance method» in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.

Если вы разработчик Python, есть большая вероятность, что вы столкнулись с ошибкой TypeError: Missing 1 Required Positional Argument: ‘self’ в какой-то момент вашего пути кодирования. Эта ошибка возникает, когда вы пытаетесь вызвать метод для экземпляра класса без передачи ссылки на этот экземпляр в качестве первого аргумента. В этом посте мы расскажем, что означает эта ошибка, как ее исправить и некоторые распространенные сценарии, в которых она может возникнуть.

Понимание ошибки

Допустим, у вас есть класс с именем SomeClass с помощью метода, названного some_method. Вы создаете экземпляр этого класса с именем some_instanceа затем попытаться вызвать some_method метод для этого экземпляра:

class SomeClass:
    def some_method(self, arg1):
        # do something

some_instance = SomeClass()
some_instance.some_method("test")

Войти в полноэкранный режимВыйти из полноэкранного режима

Если вы запустите этот код, вы получите следующую ошибку:

TypeError: some_method() missing 1 required positional argument: 'arg1'

Войти в полноэкранный режимВыйти из полноэкранного режима

Сообщение об ошибке указывает на отсутствие обязательного аргумента для some_method метод. Но почему это происходит? Ответ кроется в первом аргументе определения метода: self.

В Python классы имеют специальный параметр с именем self который используется для ссылки на экземпляр класса. Когда вы определяете метод в классе, первым параметром всегда должен быть self, даже если вам не нужно использовать его внутри метода. Это связано с тем, что Python автоматически передает экземпляр класса в качестве первого аргумента при вызове метода для экземпляра.

Исправление ошибки

Чтобы исправить ошибку TypeError: Missing 1 Required Positional Argument: ‘self’, вам нужно убедиться, что вы передаете ссылку на экземпляр класса в качестве первого аргумента при вызове метода для этого экземпляра.

Используя предыдущий пример, вам нужно будет изменить код, чтобы включить self параметр в определении метода, например:

class SomeClass:
    def some_method(self, arg1):
        # do something

some_instance = SomeClass()
some_instance.some_method(some_instance, "test")

Войти в полноэкранный режимВыйти из полноэкранного режима

Обратите внимание, что мы переходим some_instance в качестве первого аргумента some_method метод. Это говорит Python передать экземпляр класса в качестве первого аргумента, так что self параметр внутри метода указывает на правильный экземпляр.

Общие сценарии

Теперь, когда вы понимаете, что означает ошибка TypeError: Missing 1 Required Positional Argument: ‘self’ и как ее исправить, давайте рассмотрим некоторые распространенные сценарии, в которых вы можете столкнуться с этой ошибкой в ​​своем коде.

Отсутствует параметр «я»

Наиболее распространенная причина ошибки TypeError: Missing 1 Required Positional Argument: ‘self’ ошибка просто в том, что вы забыли включить self параметр в определении метода. Если вы определяете метод без self в качестве первого параметра вы получите эту ошибку при попытке вызвать этот метод для экземпляра класса.

class SomeClass:
    def some_method(arg1):  # missing 'self' parameter
        # do something

some_instance = SomeClass()
some_instance.some_method("test")

Войти в полноэкранный режимВыйти из полноэкранного режима

Чтобы исправить эту ошибку, просто добавьте self параметр определения метода.

Неверный первый параметр

Другим распространенным сценарием является передача неправильного объекта в качестве первого аргумента при вызове метода для экземпляра. Например, вы можете случайно передать другой экземпляр того же класса или совершенно не связанный объект.

class SomeClass:
    def some_method(self, arg1):
        # do something

some_instance1 = SomeClass()
some_instance2 = SomeClass()
some_instance1.some_method(some_instance2, "test")  # incorrect first parameter

Войти в полноэкранный режимВыйти из полноэкранного режима

В этом случае Python будет интерпретировать some_instance2 как self параметр внутри some_method метод, который вызовет ошибку TypeError: Missing 1 Required Positional Argument: ‘self’.

Чтобы исправить эту ошибку, убедитесь, что вы передаете правильный экземпляр класса в качестве первого аргумента при вызове метода для этого экземпляра.

Неверное имя метода

Наконец, можно получить ошибку TypeError: Missing 1 Required Positional Argument: ‘self’, если вы случайно вызовете несуществующий метод для экземпляра класса. Это может произойти, если вы неправильно написали имя метода или вызвали метод, которого нет в определении класса.

class SomeClass:
    def some_method(self, arg1):
        # do something

some_instance = SomeClass()
some_instance.nonexistent_method("test")  # incorrect method name

Войти в полноэкранный режимВыйти из полноэкранного режима

В этом случае Python не сможет найти nonexistent_method метод в SomeClass определение класса, что приведет к ошибке TypeError: Missing 1 Required Positional Argument: ‘self’.

Чтобы исправить эту ошибку, убедитесь, что вы вызываете правильное имя метода для экземпляра класса.

Заключение

Ошибка TypeError: Missing 1 Required Positional Argument: ‘self’ является распространенной ошибкой, с которой разработчики Python могут столкнуться при работе с классами и методами. Чтобы исправить эту ошибку, вам нужно убедиться, что вы включили self параметр в определении метода и передачу ссылки на экземпляр класса в качестве первого аргумента при вызове метода для этого экземпляра. Поняв причины и решения этой ошибки, вы сможете писать более качественный код Python и избегать потенциальных ошибок в своих программах.

We need to instantiate or call classes in Python before accessing their methods. If we try to access a class method by calling only the class name, we will raise the error “missing 1 required positional argument: ‘self’”.

This tutorial will go through the definition of the error in detail. We will go through two example scenarios of this error and learn how to solve each.


Table of contents

  • Missing 1 required positional argument: ‘self’
  • Example #1: Not Instantiating an Object
    • Solution
  • Example #2: Not Correctly Instantiating Class
    • Solution
  • Summary

Missing 1 required positional argument: ‘self’

We can think of a class as a blueprint for objects. All of the functionalities within the class are accessible when we instantiate an object of the class.

“Positional argument” means data that we pass to a function, and the parentheses () after the function name are for required arguments.

Every function within a class must have “self” as an argument. “self” represents the data stored in an object belonging to a class.

You must instantiate an object of the class before calling a class method; otherwise, self will have no value. We can only call a method using the class object and not the class name. Therefore we also need to use the correct syntax of parentheses after the class name when instantiating an object.

The common mistakes that can cause this error are:

  • Not instantiating an object of a class
  • Not correctly instantiating a class

We will go through each of the mistakes and learn to solve them.

Example #1: Not Instantiating an Object

This example will define a class that stores information about particles. We will add a function to the class. Functions within classes are called methods, and the method show_particle prints the name of the particle and its charge.

class Particle:

   def __init__(self, name, charge):

       self.name = name

       self.charge = charge

   def show_particle(self):

       print(f'The particle {self.name} has a charge of {self.charge}')

To create an object of a class, we need to have a class constructor method, __init__(). The constructor method assigns values to the data members of the class when we create an object. For further reading on the __init__ special method, go to the article: How to Solve Python TypeError: object() takes no arguments.

Let’s try to create an object and assign it to the variable muon. We can derive the muon object from the Particle class, and therefore, it has access to the Particle methods. Let’s see what happens when we call the show_particle() method to display the particle information for the muon.

muon = Particle.show_particle()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
muon = Particle.show_particle()

TypeError: show_particle() missing 1 required positional argument: 'self'

The code fails because we did not instantiate an object of Particle.

Solution

To solve this error, we have to instantiate the object before we call the method show_particle()

muon = Particle("Muon", "-1")

muon.show_particle()

If we run the code, we will get the particle information successfully printed out. This version of the code works because we first declared a variable muon, which stores the information about the particle Muon. The particle Muon has a charge of -1. Once we have an instantiated object, we can call the show_particle() method.

The particle Muon has a charge of -1

Note that when you call a method, you have to use parentheses. Using square brackets will raise the error: “TypeError: ‘method’ object is not subscriptable“.

Example #2: Not Correctly Instantiating Class

If you instantiate an object of a class but use incorrect syntax, you can also raise the “missing 1 required positional argument: ‘self’” error. Let’s look at the following example:

proton = Particle

proton.show_particle()

The code is similar to the previous example, but there is a subtle difference. We are missing parentheses! If we try to run this code, we will get the following output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
proton.show_particle()

TypeError: show_particle() missing 1 required positional argument: 'self'

Because we are missing parentheses, our Python program does not know that we want to instantiate an object of the class.

Solution

To solve this problem, we need to add parentheses after the Particle class name and the required arguments name and charge.

proton = Particle("proton", "+1")

proton.show_particle()

Once the correct syntax is in place, we can run our code successfully to get the particle information.

The particle proton has a charge of +1

Summary

Congratulations on reading to the end of this tutorial. The error “missing 1 required argument: ‘self’” occurs when you do not instantiate an object of a class before calling a class method. You can also raise this error if you use incorrect syntax to instantiate a class. To solve this error, ensure you instantiate an object of a class before accessing any of the class’ methods. Also, ensure you use the correct syntax when instantiating an object and remember to use parentheses when needed.

To learn more about Python for data science and machine learning, go to the online courses page for Python.

Have fun and happy researching!

The Python error TypeError: missing 1 required positional argument: ‘self’ usually occurs if you call a method directly on a class – rather than an instance of that class.

Here’s what the error looks like:


Traceback (most recent call last):
 File /dwd/sandbox/test.py, line 9, in <module>
  print(movie.get_title())
     ^^^^^^^^^^^^^^^^^
TypeError: Movie.get_title() missing 1 required positional argument: self

When you call a method on a Python object, a parameter (conventionally named self) is implicitly passed to it as its first argument. 

Woman thinking

The self parameter represents the object’s state and is equivalent to the this keyword in JavaScript, PHP, C++, etc.

That said, you should always reserve the first parameter of your non-static methods for the object instance.


class Movie:
    # self defined as the first parameter for the constructor 
    def __init__ (self, name):
        self.name = name
 
    def get_title(self):
        return self.name

Unlike keyword arguments, the order of positional arguments matters in Python, and you’ll have to pass them to the respective method in the order they are defined.

If you call the method get_title() directly on the class Movie, the object’s instance (self) isn’t passed to it. And since it expects one, Python will throw the «TypeError: missing 1 required positional argument: ‘self'».

To fix it, instantiate the class and call your method on the instantiated object. And the error would go away. Alternatively, you can use static methods if you don’t need the self parameter.

Let’s get a little bit deeper.

How to fix missing 1 required positional argument: ‘self’

As mentioned earlier, there are two options to fix the error:

  1. Instantiate the class
  2. Use static methods

Let’s explore each approach with examples.

1) Instantiate the class: The self parameter is only passed to methods if called on an object. That said, you can fix the error by instantiating the class and calling the method on the object instance.


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

    def get_title(self):
        return self.name

movie = Movie()
print(movie.get_title())

Or without storing the object’s instance in a variable:


# Instantiating the class without storing the instance
print(Movie().get_title())

2) Use static methods: If there’s no reference to the self parameter in your method, you can make it static. As a result, you’ll be able to call it directly on the class:


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

    @staticmethod
    def play_movie():
        return 'playing ...'

print(Movie.play_movie())

Please note you need to remove self in the method definition as well. Otherwise, the method keeps expecting the self parameter.

And that’s how you fix the this type error! I hope this quick guide fixed your problem.

Thanks for reading.

Author photo

Reza Lavarian Hey 👋 I’m a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @rezalavarian

  1. Not Instantiating an Object in Python
  2. Incorrectly Instantiating a Class Object in Python
  3. Fix the TypeError: missing 1 required positional argument: 'self' Error in Python
  4. Conclusion

Python TypeError: Missing 1 Required Positional Argument

Classes are one of the fundamental features of Object-Oriented Programming languages. Every object belongs to some class in Python.

We can create our class as a blueprint to create objects of the same type. We use the class keyword to define a class in Python.

A very important feature in Python is using the self attribute while defining classes. The self attribute represents the object’s data and binds the arguments to the object.

This tutorial will discuss the TypeError: missing 1 required positional argument: 'self' error in Python and how we can solve it.

Let us discuss the situations where this error is raised.

Not Instantiating an Object in Python

Positional arguments refer to the data we provide a function with. For creating class objects, we use a constructor.

If the class requires any data, we must pass it as arguments in the constructor function.

This error is raised when we forget to instantiate the class object or wrongly instantiate the class instance.

See the code below.

class Delft:
   def __init__(self, name):
       self.name = name
   def fun(self):
       return self.name

m = Delft.fun()
print(m)

Output:

TypeError: fun() missing 1 required positional argument: 'self'

In the above example, we get the error because we forget to instantiate the instance of the class and try to access the function of the class. As a result, the self attribute is not defined and cannot bind the attributes to the object.

Note that this is a TypeError, which is raised in Python while performing some unsupported operation on a given data type. It is not supported to directly access the class method without creating an instance.

Incorrectly Instantiating a Class Object in Python

Another scenario where this error can occur is when we incorrectly instantiate the class object. This can be a small typing error like ignoring the parentheses or not providing the arguments.

For example:

class Delft:
   def __init__(self, name):
       self.name = name
   def fun(self):
       return self.name

m = Delft
a = m.fun()
print(a)

Output:

TypeError: fun() missing 1 required positional argument: 'self'

Let us now discuss how to fix this error in the section below.

Fix the TypeError: missing 1 required positional argument: 'self' Error in Python

To fix this error, we can create the class instance and use it to access the class method.

See the code below.

class Delft:
   def __init__(self, name):
       self.name = name
   def fun(self):
       return self.name

m = Delft('Stack')
a = m.fun()
print(a)

Output:

In the example, we first create an instance of the class. This is then used to access the class method to return some value and print it; the error is fixed.

Another fix involves the use of static methods. Static methods are functions bound to a particular class and not to an object.

We can use the @staticmethod decorator to create such methods.

For example:

class Delft:
   def __init__(self, name):
       self.name = name
   @staticmethod
   def fun(abc):
       return abc

a = Delft.fun('Stack')
print(a)

Output:

In the above example, we changed the fun() function to a static function. This way, we could use it without instantiating any class objects.

Conclusion

This tutorial discussed the TypeError: missing 1 required positional argument: 'self' error in Python and how we can solve it.

We discussed situations where this error might occur and how to fix the error by instantiating the object of the class. We can also use static methods to work around this error.

Понравилась статья? Поделить с друзьями:
  • Missing values keyword ошибка sql
  • Missing texture detected blender ошибка
  • Missing sql property delphi ошибка
  • Missing select keyword ошибка sql
  • Missing right parenthesis oracle ошибка