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.

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 до момента завершения рабочего потока.

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.

👇 Continue Reading

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

👇 Continue Reading

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: @rlavarian

Are you having difficulties with the TypeError: Missing 1 required positional argument: ‘self’ in Python? If yes, let’s follow our article. We will give you some solutions to fix it.

What is the cause of the error “Missing 1 required positional argument: ‘self’”?

This is a common error that many beginners encounter:

class TestSelf:
  	def __init__(self):
      	print("Check label")
  	def getTest(self):
      	pass  # dummy code

t = TestSelf.getTest()
print(t)

They might want that the snippet will print:

Check label
None

But the Python runtime gave the error:

Traceback (most recent call last):
  line 6, in <module>
    t = TestSelf.getTest()
TypeError: TestSelf.getTest() missing 1 required positional argument: 'self'

Why does the first program result in an error? In fact, if you fix it, “self” is automatically provided to the constructor and methods. So what is wrong here?

To understand why does this error occur and how to fix it, you need to understand how classes work in Python 3.

Class Variable

The class construction includes a definition of class variables. Since the class owns class variables, they are shared by all class instances. Therefore, unless you initialize a variable using the class variable, it will typically have the same value for every instance.

Class variables are typically defined independently of any methods and by convention, it positioned immediately below the class header and before the constructor function and other methods.

For example, we have a simple class variable:

class TestSelf:
 	test1_type = "Check label"

The value "Check label" is given to the ‘test1_type’ variable in this instance. Typically, a class contains numerous data members, so when we create an instance, print the variable by using dot notation:

class TestSelf:
  	test1_type = "Check label" 

test_type = TestSelf
print(test_type.test1_type)

Output:

Check label

Instance Variable

Instance variables are possessed by instances of the class. This implies that the instance variables are distinct for instance of a class or each object.

Don’t like as class variables, instance variables are specified within methods.

For example:

class TestSelf:
    def __init__(self, type, length):
        self.type = "Check label"
        self.length = "10"

In this example, “type” and “length” are instance variables.

These variables must be defined before they may be supplied as parameters to the constructor method or another method when creating a TestSelf object. In Python 2, the compiler performs it implicitly, but in Python 3, you must explicitly mention it in the constructor and member functions.

How to solve the error “TypeError: missing 1 required positional argument: ‘self’”?

Add the () after class name

Because there isn’t an instance variable in the article’s first example, you just need to add the () after class name ‘TestSelf’ as the following:

class TestSelf:
    def __init__(self):
        print("Check label")
    def getTest(self):
        pass  # Dummy code

t = TestSelf().getTest()
print(t)

Output:

Check label
None

Make the function a static method of the class

Make the function a static method of the class if method 1 didn’t work :

class TestSelf:
    def __init__():
        print("Check label")
    def getTest():
        pass  # Dummy code

t = TestSelf.getTest()
print(t)

Output:

None

Summary

We hope you enjoy our article about the TypeError: missing 1 required positional argument: ‘self’ in Python. If you hane any questions or problems, let’s contact us by leaving comment below. Thanks for reading! 

Maybe you are interested:

  • typeerror: missing 1 required positional argument: ‘self’
  • TypeError: Object of type bytes is not JSON serializable
  • TypeError: sequence item 0: expected str instance, int found
  • TypeError: slice indices must be integers or None or have an __index__ method

Hello, I’m Larry C. Mae. You can call me Larry. I appreciate learning and sharing my programming language expertise. Python, C, HTML, and Machine Learning/Deep Learning/NLP are some of my strong points. If you’re having trouble with my articles, let’s stick with them.


Full Name: Larry C. Mae

Name of the university: HCMUTE
Major: AI
Programming Languages: Python, C, HTML, Machine Learning/Deep Learning/NLP

Понравилась статья? Поделить с друзьями:
  • Mivue j60 ошибка карты памяти что делать
  • Miui ошибка лаунчера
  • Miui ошибка google play
  • Miui sdk ошибка
  • Mitsubishi ошибка корректора фар 23