0

Please explain def __init__(self) in embedded for every test case starts with it.

I am new to python

11th May 2017, 5:27 PM
siva ram
siva ram - avatar
3 Antworten
+ 7
__init__ is one of the so-called *magic* methods and by far the most important obe, when it comes to class definition. Basically, it tells Python how the class instances (objects) are initialized, when created. Let's consider the following example: class Ford(): def __init__(self, color, make): self.color = "Black" self.make = "Model T" You have just created a new class - Ford() Now, if you initialize it by assigning a variable to it: my_car = Ford("Red", "Mustang") it looks into the class definition. the definition tells Python to initialize the object with two attributes - color and make. You passed two arguments to it - "Red" and "Mustang" - which mean a desired color and selected make, respectively. Nevertheless, the current definition of the Ford() class makes all its instances "Black" in color and "Model T" in make. Take a look at "self" there and at its proper use. It tells Python to distinguish the attributes passed by you to each of the objects separately. So you can choose to specify other colors and makes... theoretically ;)
11th May 2017, 5:44 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
@Amaras A The parentheses are reduntant in this case, you're right. But including them does not make the code bad. Besides, it's a habit I learned when declaring class that inherit from others. class B(): pass class A(B): pass ;)
11th May 2017, 8:47 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
I (and other Python developers) call them "dunders" for "double under" method. Other than that, @Kuba only put unnecessary parenthesis in the statement "class Ford():" Brilliant explanation. +1
11th May 2017, 7:54 PM
Amaras A
Amaras A - avatar