[SOLVED] I need an explanation through my code, where do we need to define init method and declare "self". How to call a function in each cases give in my code

Issue

I need to understand these things in python here are some codes. I want a nice description of it.
When I used the first code, "self" was necessary, When I used the second code "self" gave me an error. How?

class Sample():
    def example(self, x, y):
        z = x+ y
        return print(z)

x = Sample()
x.example(1,2)

class Sample():
    def example(x, y):
        z = x+ y
        return print(z)
Sample.example(1,2)

and this code gives me an error, I don’t know where I am wrong

class Sample():
    def __init__(self, x, y):
        self.x = x
        self.y =y

    def example(self):
        z = self.x + self.y
        return print(z)

x = Sample()
x.example(1,2)

Error

Traceback (most recent call last):
  File "c:\Users\Lenovo\Documents\PP\Advance python\example.py", line 13, in <module>
    x = Sample()
TypeError: __init__() missing 2 required positional arguments: 'x' and 'y'

Another code with error

def example(self):
    z = self.x + self.y
    return print(z)

example(1,2)

Error

Traceback (most recent call last):
  File "c:\Users\Lenovo\Documents\PP\Advance python\example.py", line 8, in <module>
    example(1,2)
TypeError: example() takes 1 positional argument but 2 were given

I would really appreciate the help.

Solution

The __init__ method is a constructor so it essentially initializes the attributes of the object. So you should pass the arguments when you are creating the object. When you use self that means those attribute/methods relates to the same class.

class Sample:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def example(self):
        z = self.x + self.y
        return print(z)


x_object = Sample(1, 2)
x_object.example()

So rather than passing the arguments to x.example you should pass them to Sample()

Answered By – Old_Arrack

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published.