Reputation:
Hello I am trying to understand __init__
in class in Python.I understood how classes work but i could not understand 1 thing
here is code:
class Computer:
def __init__(self, name, cpu, ram, hdd, ssd):
self.name = name
self.cpu = cpu
self.ram = ram
self.hdd = hdd
self.ssd = ssd
def config(self):
print("Configuration of computer is: ", self.name, self.cpu, self.ram, self.hdd, self.ssd )
computer1 = Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")
computer1.config()
why and how arguments Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")
are passed to __init__(self, name, cpu, ram, hdd, ssd)
automatically?why we are writing this arguments in class parentheses and not separately like this:
computer1.__init__("HP ", "i7 ", "16gb ", "1TB ", "256GB")
how the code can understand that arguments written in Computer's parentheses have to be passed to __init__
?
Upvotes: 2
Views: 155
Reputation: 131
This is how python works. Probably it was designed like that because some classes/structures are written in pure C.
For example.
When you want to implement custom class and implement for it len()
function, so you could get length of it by calling len(instance_of_your_class)
. Then all what you have to do is implement method __len__()
in your class.
On the other hand, you have class list
in python. This class is implement in C, cause it has to be very fast. Then when you call len(instance_of_list)
interpreted will call __len__
, which will call equavilent function in C.
From this design comes lot of benefits. One example is method __getitem__
. You implement so you could be able to get elements with instalce_of_class[2]
. But it also give you ability to use in
(if value in instance_of_class
).
You can read about methods like that. In python jargon they are dunder
methods.
Upvotes: 1
Reputation: 399
because The __init__
method is roughly what represents a constructor in Python. When you call Computer("HP ","i7 ","16gb ","1TB ","256GB")
Python creates an object for you, and passes it as the first parameter to the __init__
method. Any additional parameters(more than the five you declared) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.
Upvotes: 4