Python

When to use __init__ inside classes?

March 24, 2022

When to use __init__ inside classes?

In this article we will learn when to use __init__ inside skin classes and why this method is so useful when we are working with Object Oriented.

When to use __init__ thumb

What’s up programmer, how are you? Let’s learn more about Python!

__init__ is a feature in other languages known as a constructor

And this method will always be started when creating an object from your class

So, you have the possibility to start properties already with predetermined values for you to follow the flow of your code

In this __init__ method, we can pass a parameter called self, which deals with the object in question

That is, from self, you access the current instance of the object, directing some value to some property

See it in action:

class Humano:
 def __init__(self, name, age):
  self.name = name
  self.age = age
 def whoAmI(self):
  print("Hello, I am " + self.name)

matheus = Humano("Matheus", 29)
matheus.whoAmI()

Here in this example, we create a Human class that takes parameters like name and age

And the way we have to initialize this object created below as matheus, with a name and age is through __init__

See that we use it together with self, to determine the initial values of the properties of our object that comes from the Human class

And the output of the file is this:

Hello, I am Matheus

Conclusion

In this article we learned  when to use __init__ inside classes and also its functionality in a program written in Python

We use it to initialize our objects that are created from classes with values determined by us in their initialization

In other languages __init__ is known as a constructor

Want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x