Examples of using the method __init__ on different types of objects in Python
The method
__init__
is a special method in Python that is called automatically when we create an object. This way, the method can be used to initialize the object and assign values to its attributes. Here are some examples of how the init method can be used on different types of objects in Python:
Simple class objects:
We have a basic example of creating a Python class called “Person”. The class has a special method called “ init ” which is being called when we create an object of the class. This way, the method receives two arguments, “name” and “age”, which can be assigned to the attributes “name” and “age” of the Person object. In the end, we create a Person object receiving “Maria” and age of 25 and its attributes will be displayed in the console. Look:
class Person: def __init__(self, name, age): self.name = name self.age = age Person1 = Person("Maria", 25) print(Person1.name) # "Maria" print(Person1.age) # 25
Objects of more complex classes:
The class defines a constructor ( init ) to define the attributes of the class, which in this case are: make, model, year and price of the car. Next, we create an object of type “Car” and assign it the name “car1”. Finally, the attribute values of the object “car1” can be displayed in the console using the syntax “car1.attribute”, where the desired attribute name assumes “attribute”. Look:
class Car: def __init__(self, brand, model, ano, preco): self.brand = brand self.model = model self.year = year self.price = price car1 = Car("Ford", "Fiesta", 2015, 15000) print(car1.brand) # "Ford" print(car1.model) # "Fiesta" print(car1.year) # 2015 print(car1.price) # 15000
List objects:
Now we have an example that creates a list of three elements: “Maria”, 25 and “Sao Paulo”. It then uses a loop
for
to iterate over each element in the list and prints out each element. The syntax
for elemento in lista
means that the variable
elemento
will be updated on each iteration of the for loop , matching each element in the list. Thus, the loop prints each value of
elemento
using the function
print()
list1 = ["Maria", 25, "Sao Paulo"] for element in list1: print(element) # Output: # Maria # 25 # Sao Paulo
Dictionary objects:
This example creates a Python dictionary with three keys and associated values: “name” with the value “Maria”, “age” with the value 25, and “city” with the value “São Paulo”. In this way, a loop
for
is used to iterate over the dictionary items, which are the associated keys and values. The syntax means that the variable will be updated on each iteration, matching the dictionary key, and the variable will be updated with the corresponding key value. The loop prints each key and value using the . The output of this example will be “name”, “25” and “city”.
for chave, valor in dicionario1.items() chavevalor print()
dictionary1 = {"name": "Maria", "age": 25, "city": "Sao Paulo"} for key, value in dictionary1.items(): print(key) # "nome" print(value) # 25 # Output: # nome # 25 # cidade
Custom class objects:
And finally, we have the following example creating an “Animal” class that has a constructor to define the name and age of the animal.
The class also has a “speak” method that displays the animal’s name. Next, we create the “Dog” class, which inherits the attributes and methods of the “Animal” class. The constructor of the “Dog” class adds a new attribute, “raza”, and calls the constructor of the “Animal” class. We created the “dog1” object as an instance of the “Dog” class and the “talk” method is being called. The “speak” method displays the name of the animal, which in this case is “Fido”. The output of this example will be “The animal says: Fido”. Look:
class Animal: def __init__(self, name, age): self.name = name self.age = age def speak(self): print("The animal says:") print(self.name) class dog(Animal): def __init__(self, name, age, raza): super().__init__(name, age) self.raza = raza dog1 = dog("Fido", 3, "Labrador") dog.falar() # Output: # The animal says: # Fido
These are just a few examples of how the init method can be used to initialize objects in Python. In this sense, the method is a fundamental part of object-oriented programming and can be used in many classes to define the attributes and methods of an object.
The __init__() Function
The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and age:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person(“John”, 36)
print(p1.name)
print(p1.age)
Note: The
__init__()
function is called automatically every time the class is being used to create a new object.
init python: Learn how to use __init__ to initialize objects in python
Python init method is a special function that we can apply to initialize a class. When we create an object of the class, the method is automatically applied and defines the object’s initial behavior. In this sense, we can use the class object as a pointer to the object being initialized, accessing the class’s attributes and methods, and performing any other operations necessary to initialize the object.In this article, we’ll explore the method __init__ in Python. Thus, learning about how we can use it to initialize classes, including what it is and how it can be applied to maintain data integrity. We’ll discuss how to create a method __init__ and the syntax needed to make it work. In addition, also learn about how to add elements efficiently and use both knowledge to improve your code.
Table of Contents
Python __new__ and __init__ Examples
To better understand the differences between
__new__
and
__init__
, let’s take a look at a simple example:
class Person: def __new__(cls, name, age): print("Creating a new Person object") instance = super().__new__(cls) return instance def __init__(self, name, age): print("Initializing the Person object") self.name = name self.age = age person = Person("John Doe", 30) print(f"Person's name: {person.name}, age: {person.age}") # Creating a new Person object # Initializing the Person object # Person's name: John Doe, age: 30
In this example, we can see how the
__new__
method is called before the
__init__
method, and how they work together to create and initialize the
Person
object.
The INIT function
The INIT function initializes the data structures required by the rest of the computation of the aggregate. For example, if you write a C function, the INIT function can set up large objects or temporary files for storing intermediate results. The INIT function returns the initial result of the aggregate, which is of the state type.
The INIT function can take one or two arguments. The first argument must be the same type as the column that is aggregated. The database server uses the type of the first argument to resolve overloaded INIT functions.
For C and Java™, the first argument of the INIT function is a placeholder argument and always has a null value. Therefore, all functions that serve as INIT functions must be defined with the HANDLESNULLS modifier.
Python __init__() Function
How the __init__ method can be used to implement inheritance in Python
The method
__init__
can is being used to implement inheritance in Python, which is a way of creating classes that inherit behaviors and attributes from other classes. This is done by creating a new class that inherits from an existing class by using the keyword
class
followed by the name of the new class and the name of the base class in quotes.
You can then define the attributes and methods of the new class within the base class using the method to initialize the attributes of the new class. Also, you can override base class methods by using the keyword
def
to provide new implementations for those methods in the new class.
For example, suppose you want to create an automobile class that inherits from a vehicle class. So we can do it like this:
class Car(Vehicle): def __init__(self, make, model, year): Vehicle.__init__(self, make, model, year) self.number_of_doors = 4 self.color = "red" def start(self): print("Starting the engine...")
Here, the class
Car
inherits from the class
Vehicle
and defines a new attribute
number_of_doors
and a new method
start()
that overrides the method
start()
of the class
Vehicle
.
Thus, we are using the new class
Car
to create car objects that inherit behaviors and attributes from the class
Vehicle
and add new behaviors and attributes specific to cars.
How Does __init__() Method Work?
The python __init__ method is declared within a class and is used to initialize the attributes of an object as soon as the object is formed. While giving the definition for an __init__(self) method, a default parameter, named ‘self’ is always passed in its argument. This self represents the object of the class itself. Like in any other method of a class, in case of __init__ also ‘self’ is used as a dummy object variable for assigning values to the data members of an object.
The __init__ method is often referred to as double underscores init or dunder init for it has two underscores on each side of its name. These double underscores on both the sides of init imply that the method is invoked and used internally in Python, without being required to be called explicitly by the object.
This python __init__ method may or may not take arguments for object initialisation. You can also pass default arguments in its parameter. However, even though there is no such concept of Constructor Overloading in Python, one can still achieve polymorphism in the case of constructors in Python on the basis of its argument.
Also Read: Set in Python – How to Create a Set in Python?
Parameters in init in Python
It can take any number of arguments in it while the first parameter that will be passed in it will always be self.
Code:
Output:
Explanation:
In the above example, a class Trip is created, and an object ‘T’ is created to invoke the methods and attributes. As soon as the object is created, the__init__ method is initialized with values India and London, which are assigned to to_city and from_city, respectively. The self keyword represents the current instance of the object. So when the holiday() method is run, it prints out the values of from_city and to_city, which are London and India, respectively.
Init in Python: Syntax and Examples
We can declare a __init__ method inside a class in Python using the following syntax:
class class_name(): def __init__(self): # Required initialisation for data members # Class methods … …
Let’s take an example of a class named Teacher in Python and understand the working of __init__() method through it better.
class Teacher: # definition for init method or constructor def __init__(self, name, subject): self.name = name self.subject = subject # Random member function def show(self): print(self.name, " teaches ", self.subject) T = Teacher('Preeti Srivastava', "Computer Science") # init is invoked here T.show()
Now, for the scenarios where you are required to achieve polymorphism through __init__() method, you can go with the following syntax.
class class_name(): def __init__(self, *args): Condition 1 for *args: # Required initialisation for data members Condition 2 for *args: # Required initialisation for data members ……… ……… # Class methods … …
In this case, the type of argument passed in place of *args decide what kind of initialisation has to be followed. Take a look at the example given below to get some more clarity on this.
class Teacher: def __init__(self, *args): # Naming the teacher when a single string is passed if len(args)==1 & isinstance(args[0], str): self.name = args[0] # Naming the teacher as well as the subject elif len(args)==2: self.name = args[0] self.sub = args[1] # Storing the strength of the class in case of a single int argument elif isinstance(args[0], int): self.strength = args[0] t1 = Teacher("Preeti Srivastava") print('Name of the teacher is ', t1.name) t2 = Teacher("Preeti Srivastava", "Computer Science") print(t2.name, ' teaches ', t2.sub) t3 = Teacher(32) print("Strength of the class is ", t3.strength)
Types of __init__ Constructor
There are mainly three types of Python __init__ constructors:
- Default __init__ constructor
- Parameterised __init__ Constructor
- __init__ With Default Parameters
The Default __init__ Constructor
The default __init__ constructor in Python is the constructor that does not accept any parameters, except for the ‘self’ parameter. The ‘self’ is a reference object for that class. The syntax for defining a default __init__ constructor is as follows:
class class_name(): def __init__(self): # Constructor statements # other class methods … …
The syntax for creating an object for a class with a default __init__ constructor is as follows:
Object_name = class_name()
Example:
class Default(): #defining default constructor def __init__(self): self.var1 = 56 self.var2 = 27 #class function for addition def add(self): print("Sum is ", self.var1 + self.var2) obj = Default() # since default constructor doesn’t take any argument obj.add()
Parameterised __init__ Constructor
When we want to pass arguments in the constructor of a class, we make use of the parameterised __init__ method. It accepts one or more than one argument other than the self. The syntax followed while defining a parameterised __init__ constructor has been given below:
class class_name(): def __init__(self, arg1, arg2, arg3, …): self.data_member1 = arg1 self.data_member2 = arg2 self.data_member2 = arg2 …… …… # other class methods … …
We declare an instance for a class with a parameterised constructor using the following syntax:
Object_name = class_name(arg1, arg2, arg3,…)
Example:
class Default(): #defining parameterised constructor def __init__(self, n1, n2): self.var1 = n1 self.var2 = n2 #class function for addition def add(self): print("Sum is ", self.var1 + self.var2) obj = Default(121, 136) #Creating object for a class with parameterised init obj.add()
The __init__ method with default parameters
As you might already know, we can pass default arguments to a member function or a constructor, be it any popular programming language. In the very same way, Python also allows us to define a __init__ method with default parameters inside a class. We use the following syntax to pass a default argument in an __init__ method within a class.
class ClassName: def __init__(self, *list of default arguments*): # Required Initialisations # Other member functions …… …….
Now, go through the following example to understand how the __init__ method with default parameters works.
class Teacher: # definition for init method or constructor with default argument def __init__(self, name = "Preeti Srivastava"): self.name = name # Random member function def show(self): print(self.name, " is the name of the teacher.") t1 = Teacher() #name is initialised with the default value of the argument t2 = Teacher('Chhavi Pathak') #name is initialised with the passed value of the argument t1.show() t2.show()
What Is Object-Oriented Programming?
Object-oriented programming (OOP) is a programming pattern that consists in defining objects and interacting with them. An object is a collection of complex variables and functions and can be used to represent real entities like a button, an airplane, or a person.
To declare, initialize, and manipulate objects in Python, we use classes. They serve as templates from which objects are created. The following diagram illustrates this idea:
We can see in the above diagram that the dog class contains specific dog characteristics, such as breed and eye color, as well as the abilities to run and walk. Let’s start by defining a class in Python.
What Is a Class?
A class defines and structures all of the objects that are created from it. You can view the class as an object factory. Let’s take the example of a fox terrier—a breed of dog. From an OOP standpoint, you can think of
dog
as a class that includes a dog’s characteristics such as its breed, or eye color. Since a Fox Terrier is a dog, we can create a dog object that will inherit the characteristics of its class. Classes use methods and constructors to create and define objects.
User-Defined And Special Methods
Methods are functions within a class that are designed to perform a specific task. Python differentiates between user-defined methods, written by the programmer, and special methods that are built into the language. A user-defined method is a function created by the programmer to serve a specific purpose. For instance, a
dog
class could have a
walk()
method that the dog object can use. The programmer creates this method and has it perform specific actions.
Special methods are identified by a double underscore at either side of their name, such as
__init__
. Python uses special methods to enhance the functionality of classes. Most of them work in the background and are called automatically when needed by the program. You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the
__new__
method, which in turn calls the
__init__
method. The
__str__
method is called when you
print()
an object. On the other hand, user-defined methods, like
stefi.run()
, are called explicitly.
The Constructor
A constructor is a special method that the program calls upon an object’s creation. The constructor is used in the class to initialize data members to the object. With our
dog
class example, you can use a constructor to assign dog characteristics to each
Fox Terrier
object. The special method
__init__
is the Python constructor.
With an understanding of object oriented programming and classes, let’s now look at how the
__init__
method works within a Python program.
The Importance of Objects in Python
We don’t always see it when we write a program, but objects are central to the way Python works. When we declare a simple variable in Python, an object is created in the background.If we execute the following bit of code:
breed = “Doberman”
Python uses the str class that contains properties and methods, exactly like the ones you create in your own code, except it’s all happening in the background.
6.More on Modules¶
A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. [1] (They are also run if the file is executed as a script.)
Each module has its own private namespace, which is used as the global namespace
by all functions defined in the module. Thus, the author of a module can
use global variables in the module without worrying about accidental clashes
with a user’s global variables. On the other hand, if you know what you are
doing you can touch a module’s global variables with the same notation used to
refer to its functions,
modname.itemname
.
Modules can import other modules. It is customary but not required to place all
import
statements at the beginning of a module (or script, for that
matter). The imported module names, if placed at the top level of a module
(outside any functions or classes), are added to the module’s global namespace.
There is a variant of the
import
statement that imports names from a
module directly into the importing module’s namespace. For example:
>>> from fibo import fib, fib2 >>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the
local namespace (so in the example,
fibo
is not defined).
There is even a variant to import all names that a module defines:
>>> from fibo import * >>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore ().
In most cases Python programmers do not use this facility since it introduces
an unknown set of names into the interpreter, possibly hiding some things
you have already defined.
Note that in general the practice of importing from a module or package is
frowned upon, since it often causes poorly readable code. However, it is okay to
use it to save typing in interactive sessions.
If the module name is followed by
as
, then the name
following
as
is bound directly to the imported module.
>>> import fibo as fib >>> fib.fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This is effectively importing the module in the same way that
import fibo
will do, with the only difference of it being available as
fib
.
It can also be used when utilising
from
with similar effects:
>>> from fibo import fib as fibonacci >>> fibonacci(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Note
For efficiency reasons, each module is only imported once per interpreter
session. Therefore, if you change your modules, you must restart the
interpreter – or, if it’s just one module you want to test interactively,
use
importlib.reload()
, e.g.
import importlib;
importlib.reload(modulename)
.
6.1.Executing modules as scripts¶
When you run a Python module with
python fibo.py
the code in the module will be executed, just as if you imported it, but with
the
__name__
set to
"__main__"
. That means that by adding this code at
the end of your module:
if __name__ == “__main__”: import sys fib(int(sys.argv[1]))
you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:
$ python fibo.py 50 0 1 1 2 3 5 8 13 21 34
If the module is imported, the code is not run:
>>> import fibo >>>
This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).
6.1.The Module Search Path¶
When a module named
spam
is imported, the interpreter first searches for
a built-in module with that name. These module names are listed in
sys.builtin_module_names
. If not found, it then searches for a file
named
spam.py
in a list of directories given by the variable
sys.path
.
sys.path
is initialized from these locations:
-
The directory containing the input script (or the current directory when no file is specified).
-
PYTHONPATH
(a list of directory names, with the same syntax as the shell variable
PATH
). -
The installation-dependent default (by convention including a
site-packages
directory, handled by the
site
module).
More details are at The initialization of the sys.path module search path.
Note
On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. In other words the directory containing the symlink is not added to the module search path.
After initialization, Python programs can modify
sys.path
. The
directory containing the script being run is placed at the beginning of the
search path, ahead of the standard library path. This means that scripts in that
directory will be loaded instead of modules of the same name in the library
directory. This is an error unless the replacement is intended. See section
Standard Modules for more information.
6.1.“Compiled” Python files¶
To speed up loading modules, Python caches the compiled version of each module
in the
__pycache__
directory under the name
module.version.pyc
,
where the version encodes the format of the compiled file; it generally contains
the Python version number. For example, in CPython release 3.3 the compiled
version of spam.py would be cached as
__pycache__/spam.cpython-33.pyc
. This
naming convention allows compiled modules from different releases and different
versions of Python to coexist.
Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. This is a completely automatic process. Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures.
Python does not check the cache in two circumstances. First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. Second, it does not check the cache if there is no source module. To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module.
Some tips for experts:
-
You can use the
-O
or
-OO
switches on the Python command to reduce the size of a compiled module. The
-O
switch removes assert statements, the
-OO
switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an
opt-
tag and are usually smaller. Future releases may change the effects of optimization. -
A program doesn’t run any faster when it is read from a
.pyc
file than when it is read from a
.py
file; the only thing that’s faster about
.pyc
files is the speed with which they are loaded. -
The module
compileall
can create .pyc files for all modules in a directory. -
There is more detail on this process, including a flow chart of the decisions, in PEP 3147.
Examples of init in Python
The Default init Constructor
Here is an example of a class Car that will clarify the functioning of __init__().
Code:
Output:
Explanation:
You can see in the output the order of print statements that __init__ is called first.
init with inheritance
Inheritance is a fundamental concept in OOPs. it is the way by which a class inherits the properties of another class. Here, the first class are called the base class or parent class, and the second class is called the derived class or children class.
The derived class can access the properties and methods of their parent class. In other words, the child class inherits all the methods and properties of their parent class and can add more methods and properties that are unique to them(child class) only. Inside a child class, __init__() of the parent class can be called to create objects and assign values. Here is an example:
Code:
Output:
Explanation:
In the above example, when the object of the Child class is created, __init__() of the Child class is called, which first calls the __init__() of the ParentClass. __init__() of the ParentClass prints out ‘Parent Class’ then print inside the Child class is executed.
6.Packages¶
Packages are a way of structuring Python’s module namespace by using “dotted
module names”. For example, the module name
A.B
designates a submodule
named in a package named . Just like the use of modules saves the
authors of different modules from having to worry about each other’s global
variable names, the use of dotted module names saves the authors of multi-module
packages like NumPy or Pillow from having to worry about
each other’s module names.
Suppose you want to design a collection of modules (a “package”) for the uniform
handling of sound files and sound data. There are many different sound file
formats (usually recognized by their extension, for example:
.wav
,
.aiff
,
.au
), so you may need to create and maintain a growing
collection of modules for the conversion between the various file formats.
There are also many different operations you might want to perform on sound data
(such as mixing, adding echo, applying an equalizer function, creating an
artificial stereo effect), so in addition you will be writing a never-ending
stream of modules to perform these operations. Here’s a possible structure for
your package (expressed in terms of a hierarchical filesystem):
sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py … effects/ Subpackage for sound effects __init__.py echo.py surround.py reverse.py … filters/ Subpackage for filters __init__.py equalizer.py vocoder.py karaoke.py …
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.
The
__init__.py
files are required to make Python treat directories
containing the file as packages (unless using a namespace package, a
relatively advanced feature). This prevents directories with a common name,
such as
string
, from unintentionally hiding valid modules that occur later
on the module search path. In the simplest case,
__init__.py
can just be
an empty file, but it can also execute initialization code for the package or
set the
__all__
variable, described later.
Users of the package can import individual modules from the package, for example:
import sound.effects.echo
This loads the submodule
sound.effects.echo
. It must be referenced with
its full name.
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
An alternative way of importing the submodule is:
from sound.effects import echo
This also loads the submodule
echo
, and makes it available without its
package prefix, so it can be used as follows:
echo.echofilter(input, output, delay=0.7, atten=4)
Yet another variation is to import the desired function or variable directly:
from sound.effects.echo import echofilter
Again, this loads the submodule
echo
, but this makes its function
echofilter()
directly available:
echofilter(input, output, delay=0.7, atten=4)
Note that when using
from package import item
, the item can be either a
submodule (or subpackage) of the package, or some other name defined in the
package, like a function, class or variable. The
import
statement first
tests whether the item is defined in the package; if not, it assumes it is a
module and attempts to load it. If it fails to find it, an
ImportError
exception is raised.
Contrarily, when using syntax like
import item.subitem.subsubitem
, each item
except for the last must be a package; the last item can be a module or a
package but can’t be a class or function or variable defined in the previous
item.
6.4.Importing * From a Package¶
Now what happens when the user writes
from sound.effects import *
? Ideally,
one would hope that this somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them all. This could take a
long time and importing sub-modules might have unwanted side-effects that should
only happen when the sub-module is explicitly imported.
The only solution is for the package author to provide an explicit index of the
package. The
import
statement uses the following convention: if a package’s
__init__.py
code defines a list named
__all__
, it is taken to be the
list of module names that should be imported when
from package import *
is
encountered. It is up to the package author to keep this list up-to-date when a
new version of the package is released. Package authors may also decide not to
support it, if they don’t see a use for importing * from their package. For
example, the file
sound/effects/__init__.py
could contain the following
code:
__all__ = [“echo”, “surround”, “reverse”]
This would mean that
from sound.effects import *
would import the three
named submodules of the
sound.effects
package.
Be aware that submodules might become shadowed by locally defined names. For
example, if you added a
reverse
function to the
sound/effects/__init__.py
file, the
from sound.effects import *
would only import the two submodules
echo
and
surround
, but not the
reverse
submodule, because it is shadowed by the locally defined
reverse
function:
__all__ = [ “echo”, # refers to the ‘echo.py’ file “surround”, # refers to the ‘surround.py’ file “reverse”, # !!! refers to the ‘reverse’ function now !!! ] def reverse(msg: str): # <– this name shadows the ‘reverse.py’ submodule return msg[::-1] # in the case of a ‘from sound.effects import *’
If
__all__
is not defined, the statement
from sound.effects import *
does not import all submodules from the package
sound.effects
into the
current namespace; it only ensures that the package
sound.effects
has
been imported (possibly running any initialization code in
__init__.py
)
and then imports whatever names are defined in the package. This includes any
names defined (and submodules explicitly loaded) by
__init__.py
. It
also includes any submodules of the package that were explicitly loaded by
previous
import
statements. Consider this code:
import sound.effects.echo import sound.effects.surround from sound.effects import *
In this example, the
echo
and
surround
modules are imported in the
current namespace because they are defined in the
sound.effects
package
when the
from...import
statement is executed. (This also works when
__all__
is defined.)
Although certain modules are designed to export only names that follow certain
patterns when you use
import *
, it is still considered bad practice in
production code.
Remember, there is nothing wrong with using
from package import
specific_submodule
! In fact, this is the recommended notation unless the
importing module needs to use submodules with the same name from different
packages.
6.4.Intra-package References¶
When packages are structured into subpackages (as with the
sound
package
in the example), you can use absolute imports to refer to submodules of siblings
packages. For example, if the module
sound.filters.vocoder
needs to use
the
echo
module in the
sound.effects
package, it can use
from
sound.effects import echo
.
You can also write relative imports, with the
from module import name
form
of import statement. These imports use leading dots to indicate the current and
parent packages involved in the relative import. From the
surround
module for example, you might use:
from . import echo from .. import formats from ..filters import equalizer
Note that relative imports are based on the name of the current module. Since
the name of the main module is always
"__main__"
, modules intended for use
as the main module of a Python application must always use absolute imports.
6.4.Packages in Multiple Directories¶
Packages support one more special attribute,
__path__
. This is
initialized to be a list containing the name of the directory holding the
package’s
__init__.py
before the code in that file is executed. This
variable can be modified; doing so affects future searches for modules and
subpackages contained in the package.
While this feature is not often needed, it can be used to extend the set of modules found in a package.
Footnotes
Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. It is not easy to define object-oriented programming, but we have already seen some of its characteristics: For example, the Time class defined in Chapter 16 corresponds to the way people record the time of day, and the functions we defined correspond to the kinds of things people do with times. Similarly, the Point and Rectangle classes correspond to the mathematical concepts of a point and a rectangle. So far, we have not taken advantage of the features Python provides to support object-oriented programming. These features are not strictly necessary; most of them provide alternative syntax for things we have already done. But in many cases, the alternative is more concise and more accurately conveys the structure of the program. For example, in the Time program, there is no obvious connection between the class definition and the function definitions that follow. With some examination, it is apparent that every function takes at least one Time object as an argument. This observation is the motivation for methods; a method is a function that is associated with a particular class. We have seen methods for strings, lists, dictionaries and tuples. In this chapter, we will define methods for user-defined types. Methods are semantically the same as functions, but there are two syntactic differences: In the next few sections, we will take the functions from the previous two chapters and transform them into methods. This transformation is purely mechanical; you can do it simply by following a sequence of steps. If you are comfortable converting from one form to another, you will be able to choose the best form for whatever you are doing.
In Chapter 16, we defined a class named
To call this function, you have to pass a Time object as an argument:
To make
Now there are two ways to call
In this use of dot notation, Time is the name of the class, The second (and more concise) way is to use method syntax:
In this use of dot notation, Inside the method, the subject is assigned to the first parameter, so in this case start is assigned to time.
By convention, the first parameter of a method is
The reason for this convention is an implicit metaphor: This change in perspective might be more polite, but it is not obvious that it is useful. In the examples we have seen so far, it may not be. But sometimes shifting responsibility from the functions onto the objects makes it possible to write more versatile functions, and makes it easier to maintain and reuse code. Exercise 1 Rewrite Here’s a version of increment (from Section 16.3) rewritten as a method:
This version assumes that Here’s how you would invoke increment:
The subject, start, gets assigned to the first parameter, self. The argument, 1337, gets assigned to the second parameter, seconds. This mechanism can be confusing, especially if you make an error. For example, if you invoke increment with two arguments, you get:
The error message is initially confusing, because there are only two arguments in parentheses. But the subject is also considered an argument, so all together that’s three.
To use this method, you have to invoke it on one object and pass the other as an argument:
One nice thing about this syntax is that it almost reads like English: “end is after start?”
The init method (short for “initialization”) is
It is common for the parameters of
stores the value of the parameter hour as an attribute of self. The parameters are optional, so if you call Time with no arguments, you get the default values.
If you provide one argument, it overrides hour:
If you provide two arguments, they override hour and minute.
And if you provide three arguments, they override all three default values. Exercise 2 Write an init method for the Point class that takes x and y as optional parameters and assigns them to the corresponding attributes. For example, here is a str method for Time objects:
When you print an object, Python invokes the str method:
When I write a new class, I almost always start by writing Exercise 3 Write a str method for the Point class. Create a Point object and print it.
By defining other special methods, you can specify the behavior Here is what the definition might look like:
And here is how you could use it:
When you apply the + operator to Time objects, Python invokes
Changing the behavior of an operator so that it works with Exercise 4 Write an add method for the Point class.
In the previous section we added two Time objects, but you
The built-in function isinstance takes a value and a class object, and returns True if the value is an instance of the class. If other is a Time object, Here are examples that use the + operator with different types:
Unfortunately, this implementation of addition is not commutative. If the integer is the first operand, you get
The problem is, instead of asking the Time object to add an integer,
And here’s how it’s used:
Exercise 5 Write an add method for Points that works with either a Point object or a tuple: Type-based dispatch is useful when it is necessary, but (fortunately) it is not always necessary. Often you can avoid it by writing functions that work correctly for arguments with different types. Many of the functions we wrote for strings will actually work for any kind of sequence. For example, in Section 11.1 we used histogram to count the number of times each letter appears in a word.
This function also works for lists, tuples, and even dictionaries, as long as the elements of s are hashable, so they can be used as keys in d.
Functions that can work with several types are called polymorphic. Polymorphism can facilitate code reuse. For example, the built-in function sum, which adds the elements of a sequence, works as long as the elements of the sequence support addition. Since Time objects provide an add method, they work with sum:
In general, if all of the operations inside a function work with a given type, then the function works with that type. The best kind of polymorphism is the unintentional kind, where you discover that a function you already wrote can be applied to a type you never planned for. It is legal to add attributes to objects at any point in the execution of a program, but if you are a stickler for type theory, it is a dubious practice to have objects of the same type with different attribute sets. It is usually a good idea to initialize all of an objects attributes in the init method. If you are not sure whether an object has a particular attribute, you can use the built-in function hasattr (see Section 15.7).
Another way to access the attributes of an object is through the
For purposes of debugging, you might find it useful to keep this function handy:
The built-in function getattr takes an object and an attribute name (as a string) and returns the attribute’s value. Exercise 6 This exercise is a cautionary tale about one of the most common, and difficult to find, errors in Python. Exercise 7 Visual is a Python module that provides 3-D graphics. It is not always included in a Python installation, so you might have to install it from your software repository or, if it’s not there, from vpython.org. The following example creates a 3-D space that is 256 units wide, long and high, and sets the “center” to be the point (128, 128, 128). Then it draws a blue sphere.
color is an RGB tuple; that is, the elements are Red-Green-Blue levels between 0.0 and 1.0 (see wikipedia.org/wiki/RGB_color_model). If you run this code, you should see a window with a black background and a blue sphere. If you drag the middle button up and down, you can zoom in and out. You can also rotate the scene by dragging the right button, but with only one sphere in the world, it is hard to tell the difference. The following loop creates a cube of spheres:
You can see my solution at thinkpython.com/code/color_space.py. |
We’d like to know about it. Please consider filling out this short survey. |
__init__ method in Python is used to initialize objects of a class. It is also called a constructor.
To completely understand the concept of __init__ method, you should be familiar with:
Prerequisites – Python Class and Objects, Self
6.Standard Modules¶
Python comes with a library of standard modules, described in a separate
document, the Python Library Reference (“Library Reference” hereafter). Some
modules are built into the interpreter; these provide access to operations that
are not part of the core of the language but are nevertheless built in, either
for efficiency or to provide access to operating system primitives such as
system calls. The set of such modules is a configuration option which also
depends on the underlying platform. For example, the
winreg
module is only
provided on Windows systems. One particular module deserves some attention:
sys
, which is built into every Python interpreter. The variables
sys.ps1
and
sys.ps2
define the strings used as primary and secondary
prompts:
>>> import sys >>> sys.ps1 ‘>>> ‘ >>> sys.ps2 ‘… ‘ >>> sys.ps1 = ‘C> ‘ C> print(‘Yuck!’) Yuck! C>
These two variables are only defined if the interpreter is in interactive mode.
The variable
sys.path
is a list of strings that determines the interpreter’s
search path for modules. It is initialized to a default path taken from the
environment variable
PYTHONPATH
, or from a built-in default if
PYTHONPATH
is not set. You can modify it using standard list
operations:
>>> import sys >>> sys.path.append(‘/ufs/guido/lib/python’)
Complete Code Example
Example 1:
class Dog: def __init__(self, dogBreed,dogEyeColor): self.breed = dogBreed self.eyeColor = dogEyeColor tomita = Dog(“Fox Terrier”,”brown”) print(“This dog is a”,tomita.breed,”and his eyes are”,tomita.eyeColor)
Example 2:
class Dog: def __init__(self): self.nbLegs = 4 tomita = Dog() print(“This dog has”,tomita.nbLegs,”legs”)
Example 3:
class Dog: def __init__(self, dogBreed=”German Shepherd”,dogEyeColor=”brown”): self.breed = dogBreed self.eyeColor = dogEyeColor tomita = Dog() print(“This dog is a”,tomita.breed,”and his eyes are”,tomita.eyeColor)
Python __init__() Function
When to Use __init__ in Python
You should use
__init__
when you need to initialize the object. For example, you might want to use
__init__
to:
- Set the object’s attributes.
-
Call the object’s superclass’
__init__
method. - Perform other initialization tasks.
Conclusion
So, to sum it all up, __init__ is a reserved method for classes in Python that basically behaves as the constructors. In other words, this method in a Python class is used for initialising the attributes of an object. It is invoked automatically at the time of instance creation for a class. This __init__ constructor is invoked as many times as the instances are created for a class. We can use any of the three types of __init__ constructors – default, parameterised, __init__ with default parameter – as per the need of our programming module. The ‘self’ is a mandatory parameter for any member function of a class, including the __init__ method, as it is a reference to the instance of the class created.
Even though Python does not support constructor overloading, the concept of constructor overloading can be implemented using the *args that are used for passing different numbers of arguments for different objects of a class. Furthermore, we can use the if-else statements for initialising the attributes according to the different types of arguments within the __init__ constructor. To know more about Classes and Objects in Python, you can check out this blog.
We have also seen how the __init__ method of a class works with inheritance. We can easily call the __init__ method of the base class within the __init__ method of the sub class. When an object for the subclass is created, the __init__ method of the sub class is invoked, which further invokes the __init__ method of the base class.
Embarking on a journey towards a career in data science opens up a world of limitless possibilities. Whether you’re an aspiring data scientist or someone intrigued by the power of data, understanding the key factors that contribute to success in this field is crucial. The below path will guide you to become a proficient data scientist.
Data Science Course Certificates |
Data Science Course Placements |
Data Science Course Syllabus |
Data Science Course Eligibility |
__init__ in Python
Syntax
We use the method
__init__
in Python to initialize a class. When we input an object of the class, the method is applied automatically. Thus, the basic syntax of the method
__init__
is as follows:
def __init__(self, *args, **kwargs): # código a ser executado durante a inicialização do objeto
The first parameter of the method
__init__
is the argument list (
*args
). We can use it to pass construction arguments to the class when we create an object. Also, if there are no construction arguments, we can pass
None
to the first parameter.
The second parameter of the method
__init__
is the initialization parameter list (
**kwargs
). We can be using it to pass initialization parameters to the class when we input an object. So the initialization parameters are being passed as an associative key-value where the key is the parameter name and the value is the parameter value.
We run the code inside the method
__init__
when we create an object. In this way, we can use the class object as a pointer to the object being initialized, accessing the class’s attributes and methods, and performing any other operation necessary to initialize the object.
In this example below, we create a class
Car
with a method
__init__
that takes three parameters (
make
,
model
and
year
). Code within the method
__init__
assigns these values to the corresponding attributes. So we also create a method
start
and a method
stop
that print information about the car. When we create an object of the class
Car
and call the
start
and methods
stop
, the code inside the method
__init__
is executed. Look:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start(self): print(f"Starting {self.make} {self.model} {self.year}") def stop(self): print(f"Stopping {self.make} {self.model} {self.year}") car = Car("Toyota", "Corolla", 2022)
Python3
|
Output:
B init calledA init called
Read: Inheritance in Python
We have covered __init__ in Python, discussed how to use __init__, and also saw some examples of using __init__ method in Python.
Constructor is a crucial concept in OOPs, and __init__ method is very similar to constructors.
Hope this article helped you in learning __init__ method, and you will be able to use it in your projects.
Related Article
Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
20 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments