Home > Software engineering >  TypeError: _init_() missing 1 required positional argument: 'self'
TypeError: _init_() missing 1 required positional argument: 'self'

Time:01-01

So, I was trying myself with classes the first time and I stumbled upon following error:

Bücher-Tutorials.py:, line 30, in Mensch:
    _init_(name="John", groesse="175cm", passwort="A", age="2")
TypeError: _init_() missing 1 required positional argument: 'self'

Here is a snippet of the snippet of the source code:

{`class Mensch:
    def _init_(self, name, age, groesse, passwort):
        self.name = name
        self.age = age
        self.groesse = groesse
        self.passwort = passwort
        def gruessen(self):
            print("Hallo,ich heiße"   name)
        gruessen(self)
    _init_(name="John", self="ad", groesse="175cm", passwort="A",age="2")```}

I tried creating an argument called self that went about ike this:

self.self = self,but it didn't work. Can anyone help me,I would be really thankful thank you,bye!

CodePudding user response:

You don't need the last line.

class Mensch:
    def __init__(self, name, age, groesse, passwort): # __init__ instead of _init_
        self.name = name
        self.age = age
        self.groesse = groesse
        self.passwort = passwort
    def gruessen(self):  # this method can now be called from outside
        print("Hallo, ich heiße "   self.name)

Bob = Mensch(name="John", age="2", groesse="175cm", passwort="A")
Bob.gruessen()

This will return

Hallo, ich heiße John

CodePudding user response:

In Python the function (or to better say method) __init__ is a [constructor][1], and if you want to call it for its class, you just have to do like this:

class MyClass:
    def __init__(self, name):
        self.name = name
MyObject = MyClass('name') # In this case the constructor is called

In Python classes, to get the self the function looks for the inizialized object:

MyObject = MyClass('name') # In MyClass.__init__ MyObject will be self

In your case you simply have to call your constructor this way:

MyObject = Mensch(name="John", self="ad", groesse="175cm", passwort="A",age="2")

Since the arguments in your __init__ prototype are positionals...

def _init_(self, name, age, groesse, passwort) #Do you see they have a specific order?

...you can call the constructor this way:

MyObject = Mensch("John", '2', "175cm", "A")

About classes


The "functions inside classes" are called instance's methods, in fact MyObject is "an instance of class Mensch.

You really shouldn't declare gruessen inside __init__, do this instead:

def __init__(self, ...):
    ...
    self.gruessen() #This is the proper way to call a method
def gruessen(self):
    print(f'Hallo,ich heiße {self.name}')
  • Related