Missing 1 required positional argument 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.

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 TypeError missing 1 required positional argument occurs in Python because of two possible causes:

This article explains why this error occurs and how you can fix it.

1. You called a function without passing the required arguments

A function in Python can have as many parameters as you define in the function definition.

For example, the following function greet() has one parameter named first_name:

def greet(first_name):
    print(f"Hello, {first_name}")

When you call this function later, you need to provide a value that will be assigned as the first_name variable. A value that you passed to a parameter is called an argument.

The error happens when you call a function that has a parameter without passing an argument for that parameter.

Let’s say you call greet() as follows:

Because there’s no parameter, Python shows the following error:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    greet()
TypeError: greet() missing 1 required positional argument: 'first_name'

To fix this error, you need to provide the required argument:

greet("Nathan")  # ✅

# Output: Hello, Nathan

If your function has many parameters, then Python will show missing x required positional arguments error, with x being the number of arguments you need to specify.

Here’s another example:

def greet(first_name, last_name):
    print(f"Hello, {first_name} {last_name}")


greet()  # ❌

Output:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    greet()
TypeError: greet() missing 2 required positional arguments: 'first_name' and 'last_name'

Again, you need to pass the required positional arguments when calling the function to fix this error.

Alternatively, you can also make the parameters optional by providing default values.

See the example below:

def greet(first_name="Nathan"):
    print(f"Hello, {first_name}")


greet()  # ✅ Hello, Nathan

The first_name parameter in the greet() function has a default value of Nathan.

The addition of this default value makes the first_name parameter optional. The default value will be used when the function is called without providing an argument for the parameter.

2. You instantiate an object without passing the required arguments

This error also occurs when you instantiate an object from a class without passing the arguments required by the __init__ method.

The __init__ method of a class is called every time you instantiate an object from a class.

Imagine you have a class named Car with an __init__ method that sets the car price as follows:

class Car:
    def __init__(self, price):
        self.price = price

Next, you try to instantiate an object without passing the argument for price:

You’ll get the following error:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    my_car = Car()
             ^^^^^
TypeError: Car.__init__() missing 1 required positional argument: 'price'

To fix this error, you need to pass the required argument price when instantiating a Car object:

my_car = Car(20000)

print(my_car.price)  # 20000

You can also provide a default value for the price parameter to avoid the error:

class Car:
    def __init__(self, price=30000):
        self.price = price


my_car = Car()

print(my_car.price)  # 30000

If the parameter has a default value, then it becomes optional. The default value will be used when the object is instantiated without passing the required argument(s).


To conclude, Python TypeError missing x required positional argument(s) is triggered when you don’t pass the required arguments when calling a function.

The error also appears when you instantiate an object from a class without passing the parameters required by the __init__ method.

To fix the error, you need to pass the x number of required arguments.

I hope this article is helpful. I’ll see you in other articles! 👋

Many developers get the error message: TypeError: __init__() missing 1 required positional argument in Python. This is a common issue when working with a class. This article will explain the cause and give the solution. Scroll down to learn!

After defining a class in Python, you try to create a new object. However, the Python program fails to run and you get the error message: TypeError: __init__() missing 1 required positional argument.

Here is the code sample that leads to the issue:

# Create a class Student
class Student:
    def __init__(self, studentName):
        self.studentName = studentName

# Create a new object: student
student = Student()

# Print the name of the object student
print(student.studentName)

As you run the code, the error message occurs:

  student = Student()
TypeError: __init__() missing 1 required positional argument: 'studentName'

Please notice that the __init__() function of the class Student() requires a value for the studentName. If you pass no value to it, the TypeError will occur, preventing the Python program from running properly.

How to fix TypeError: __init__() missing 1 required positional argument

After determining the cause, we will move on to how to fix TypeError: __init__() missing 1 required positional argument.

There are 2 ways to fix the problem:

Add value when creating the object

As mentioned above, you have to add a value inside the () when creating the object. Otherwise, the __init__() function of the class can not work, which leads to the TypeError.

The syntax is like this:

class [Object]:    
   def __init__(self, objectName):        
     self.objectName = objectName
[variable] = [Object]([Name of the object])
print([variable].objectName)

The [Name of the object] should be in a string format. As you print the object name out, the output will be this string.

Here is the code sample:

# Create a class Student
class Student:
    def __init__(self, studentName):
        self.studentName = studentName

# Create an object student with the studentName: Andy
student = Student("Andy")

# Print the studentName of the object
print(student.studentName)

The output will be:

Andy

Add value when defining the __init__ () function

You don’t have to add value when creating the object. Another way is to create a first value in the definition of the __init__() function. In this way, a new object created will automatically take this first value for its attribute.

The syntax is like this:

class [Object]:    
   def __init__(self, objectName = [Name of the object]):        
     self.objectName = objectName
[variable] = [Object]([Name of the object])
print([variable].objectName)

Instead of passing the value inside the () when creating the object, you will move this value inside the objectName parameter of the __init__() function.

Here is the code sample:

# Create a class Student
class Student:
    def __init__(self, studentName="Andy"):
        self.studentName = studentName

# Create the object Student with the studentName: Andy
student = Student()

# Print the name of the object
print(student.studentName)

The output will be:

Andy

Of course, you can still assign a new value to the attribute of the object. If you don’t want your object to have the first value, simply pass a different value to the () when creating it.

Here is the sample:

# Create a class Student
class Student:
    def __init__(self, studentName="Andy"):
        self.studentName = studentName

# Create the object with the studentName: William instead of Andy
student = Student("William")

# Print the name of the object
print(student.studentName)

The output will be:

William

Summary

In conclusion, the TypeError: __init__() missing 1 required positional argument in Python occurs when you create an object without adding a value to it. The __init__() function will have no value to initialize the object. You can fix this problem by adding the value directly inside the () when initializing or setting the first value in the definition of the __init__() function.

I am William Nguyen and currently work as a software developer. I am highly interested in programming, especially in Python, C++, Html, Css, and Javascript. I’ve worked on numerous software development projects throughout the years. I am eager to share my knowledge with others that enjoy programming!

threadBeginCard = Timer(0.1, beginCard, args=None, kwargs=None)

Я без понятия, что такое Timer(), но могу догадаться, что он делает.
Он вызывает beginCard() без позиционных (args) или именованных (kwargs) параметров по наступлению некоторого события.
Проблема в том, что ты вызываешь метод класса, т.е. фактически Class.beginCard(). Ему нужно первым параметром передать экземпляр класса, т.е. self.
Если бы ты вызывал метод экземпляра, т.е.
c = Class()
c.beginCard()
То тогда self был бы подставлен автоматически.

Вывод: создать Timer() внутри экземплярного метода, и передать ему self.beginClass в качестве функции. Обрати внимание на отсутствие скобок.

Правда, я фз что произойдёт дальше — вызов join() мне не очень нравится, так как он заблокирует поток UI до момента завершения рабочего потока.

  • Misplaced else c ошибка
  • Mismatch in the pins equivalence values ошибка p cad
  • Mismatch in datapacket валента ошибка
  • Mise 605 indesit коды ошибок
  • Mirrors edge ошибка при запуске приложения 0xc0000906