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?
CodePudding user response:
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
}
CodePudding user response:
__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