![]() |
|
[Tut] What is __init__ in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] What is __init__ in Python? (/thread-96425.html) |
[Tut] What is __init__ in Python? - xSicKxBot - 07-27-2020 What is __init__ in Python? When reading over other people’s Python code, many beginners are puzzled by the Code: __init__(self)What’s the purpose of Code: __init__(self)The reserved Python method Code: __init__()![]() While this answers the question, if you’ve got any ambition in becoming a professional Python coder, it’s not enough to know that the Code: __init__Interactive Example: Before I’ll explain it to you, let’s open your knowledge gap. Consider the following example: https://trinket.io/embed/python/fbc1b43146 Exercise: Add one argument color to the Code: __init__Let’s dive into this simple example in great detail. How to Use the __init__ Method in Practice? A Simple Example We’ll use some terms of object-oriented programming in Python to explain our example. Make sure to study the following cheat sheet (you can also download the PDF here). Click the image to get the cheat sheet (opens in a new tab). If you’re already comfortable with basic object-orientation terminologies like classes and instances, simply read on. ![]() You’ve learned that the Code: __init__The Self Argument The Code: __init__Code: selfCode: selfCode: self.color = "blue"Code: colorCode: "blue"Let’s have a look at the following basic code example: Code: class Dog: def __init__(self): self.color = "blue" bello = Dog()
print(bello.color)
# blue
However, this minimal example is unrealistic. Some dogs are brown, others are black, and only some are blue. Multiple Constructor Arguments So how can we create different dogs with different colors? We can easily achieve this by using more arguments, in addition to Code: selfCode: __init__Code: class Dog: def __init__(self, color): self.color = color bello = Dog("blue")
print(bello.color)
# blue alice = Dog("brown")
print(alice.color)
# brownIn contrast to the first example, we now define the constructor Code: __init__(self, color)The first is the Code: selfCode: colorCode: belloCode: aliceCode: colorNote that the Code: selfCode: DogCode: __init__What’s the Difference between the Constructor and the Initializer? Well, I haven’t used a very accurate terminology in the previous paragraphs. I used the term “constructor” for both the call Code: Dog()Code: __init__()Code: __init__Code: selfCode: __init__![]() What’s the Meaning of the Underscores in the __init__ Method Name? I’ve written a whole article about the meaning of the underscore in Python. Check it out if this topic interests you further. The key takeaway, however, is the following: The double underscore “__” (called “dunder“) is used to make an instance attribute or method private (cannot be accessed from outside the class) — when used as leading dunder. When used as enclosing dunder (e.g. “__init__”) it indicates that it is a special method in Python (called “magic method”). How to Use __init__ in an Inherited Class? An inherited class is a class that inherits all attributes and methods from a parent class. Here’s an example: Code: class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): Dog.__init__(self, color) self.hairs = True bello = CuteDog('brown')
print(bello.hairs)
# True print(bello.color)
# brownInheritance is very important in Python. In the example, the parent class is the class Dog you already know from above. The initializer method __init__ defines the color of this dog. Now, we also create a new class Code: CuteDogCode: DogCode: CuteDog(Dog)The interesting thing is that the __init__ method of the child class CuteDog calls the __init__ method of the parent class. This makes sense because the child class has the same attributes as the parent class—and they need to be initialized, too. The more Pythonic way, however, is to use the Code: super()Code: class Dog: def __init__(self, color): self.color = color class CuteDog(Dog): def __init__(self, color): super().__init__(color) self.hairs = True bello = CuteDog('brown')
print(bello.hairs)
# True print(bello.color)
# brownWith the help of the Code: super()Let’s have a look at a few related questions. Is __ init __ Necessary in Python? No. You can simply skip the initializer method. As a result, your class won’t have any instance attributes directly after its creation. However, you can add instance attributes dynamically at any future point in time. Here’s an example: Code: class Dog: None bello = Dog()
bello.color = "blue"
print(bello.color)
# blueHow beautiful! You can even create empty classes and “fill in” the methods and attributes later in Python. What Does __ init __ Return? The Code: __init__Code: Dog()Code: __init__Can __init__ Return a Value? No. The only return value that doesn’t cause a runtime error is Code: NoneCode: class Dog: def __init__(self, color): self.color = color return 0 bello = Dog("blue")
# TypeError: __init__() should return None, not 'int'So never use any return value in the __init__ method and you’re good to go. Where to Go from Here? Thanks for reading through the whole article. You’ve learned that the Code: __init__The article requires a thorough understanding of the Python basics. Investing time to learn and study those is vital for your success as a professional coder. To help people grow their skills in an automated, personalized way, I’ve created a free Python email course “Coffee Break Python” that grows your skill level in a seemingless way. Day after day after day… Join tens of thousands of Python coders (100% free)! |