What role do __init___ and self play?

Asked 2 years ago, Updated 2 years ago, 146 views

I usually speak C language, and sometimes I don't understand Python because it's a habit.

What do self and _init__ do in the functions below? Is there any reason why you have to write it down? I think it's because of the oop, but if you know the exact reason, please let me know

def method(self, blah):
    def __init__(?):
        ....
    ....

oop python init self

2022-09-22 10:41

1 Answers

I'll explain it with the following code

class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print self.x + ' ' + foo

a = A()

self means an instance of the object itself. Object-oriented language most of this method to deliver, but you can't see it. Defines a method of the class from the Python when self the and clear. when the methods to retrieve any self is automatically delivered.

__init__ is the constructor used by Python.

In the above code, A() is It does not hand over any parameters to the constructor _init__ and generates an object of type A as a result and returns it.

If you write A (24, 'Hello'), you need a constructor that receives two parameters Currently, __init__ does not accept any parameters, so an exception occurs.


2022-09-22 10:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.