Does the __init__ method in python mean the same as the Main method in C#?

Question:

Not really sure whether this is the sort of thing to ask here but here we go.

I recently learnt the basics of OOP in python to help with a project. I moved onto C# as a sort of extension of that, so I could create games with Unity.

I was just wondering whether the main method in C# was the same as the __init__ method in python?

Asked By: AtomProgrammer

||

Answers:

The if __name__ == "__main__": idiom matches to the public static Main() method.

The def __init__(self): method matches to the constructor of a class in C#.

class X
{
    public X() { }  // constructor in C#: same name as the class and no return type
}
Answered By: Thomas Weller

No, the __init__ method in Python corresponds to the constructor method in C#.

__init__ / constructors are called when a new instance of a class is created.

The main method of the program class in C# is only called once when the application is started.

Answered By: NineBerry

__init__ method is used during class definitions, usually storing all predefined class variables, like:

class Basket:

   def __init__(size, material, color):
       self.size = size 
       self.material = material
       self.color = color

then when you create an instance of the class Basket and pass the positional arguments the __init__ method uses them to create the object:

basket = Basket(20, 'rubber', 'brown')

then we can call the basket instance arguments like:

print(basket.size, basket.material)

Output:

20, brown
Answered By: SLDem
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.