concept _ _ init _ _ in category python

appears as: __init__
Python Workout: 50 ten-minute exercises

This is an excerpt from Manning's book Python Workout: 50 ten-minute exercises.

Table 9.1 What you need to know (view table figure)

Concept

What is it?

Example

To learn more

class

Keyword for creating Python classes

class Foo

http://mng.bz/1zAV

__init__

Method invoked automatically when a new instance is created

def __init__(self):

http://mng.bz/PAa9

__repr__

Method that returns a string containing an object’s printed representation

def __repr__(self):

http://mng.bz/Jyv0

super built-in

Returns a proxy object on which methods can be invoked; typically used to invoke a method on a parent class

super().__init__()

http://mng.bz/wB0q

dataclasses .dataclass

A decorator that simplifies the definition of classes

@dataclass

http://mng.bz/qMew

It creates a new instance of Person and holds onto it as a local variable. But then __new__ calls __init__. It passes the newly created object as the first argument to __init__, then it passes all additional arguments using *args and **kwargs, as shown in figure 9.4.

__Figure 9.4 new__ then calls __init__.

Now __init__ adds one or more attributes to the new object, as shown in figure 9.5, which it knows as self, a local variable.

Figure 9.5 __init__ adds attributes to the object.
class LoudIterator():
    def __init__(self, data):
        print('\tNow in __init__')
        self.data = data                        #1
        self.index = 0                          #2
 
    def __iter__(self):
        print('\tNow in __iter__')
        return self                             #3
 
    def __next__(self):
        print('\tNow in __next__')
        if self.index >= len(self.data):        #4
            print(
                f'\tself.index ({self.index}) is too big; exiting')
            raise StopIteration
 
        value = self.data[self.index]           #5
        self.index += 1                         #6
        print('\tGot value {value}, incremented index to {self.index}')
        return value
 
 
for one_item in LoudIterator('abc'):
    print(one_item)
Get Programming: Learn to code with Python

This is an excerpt from Manning's book Get Programming: Learn to code with Python.

31.2.1. Initializing an object with __init__

To initialize your object, you have to implement a special operation, the __init__ operation (notice the double underscores before and after the word init):

class Circle(object):
    def __init__(self):
       # code here

The __init__ definition looks like a function, except it’s defined inside a class. Any function defined inside a class is named a method.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest