{article Dive into Python}{title} {text}{/article}

Data Structures and Algorithms in Python

Instantiation
The process of creating a new instance of a class is known as instantiation. In general, the syntax for instantiating an object is to invoke the constructor of a class. For example, if there were a class named Widget, we could create an instance of that class using a syntax such asw = Widget(),
assuming that the constructor does not require any parameters. If the constructor does require parameters, we might use a syntax such as Widget(a, b, c) to construct a new instance.

instantiate
To create an instance of a class.
instance
An object that belongs to a class.

>>> import fileinfo
>>> f = fileinfo.FileInfo("/music/_singles/kairo.mp3")
>>> f.__class__
<class 'fileinfo.FileInfo'>
>>> f.__doc__
'store file metadata'
>>> f
{'name': '/music/_singles/kairo.mp3'}

You are creating an instance of the FileInfo class (defined in the fileinfo module) and assigning the
newly created instance to the variable f. You are passing one parameter, /music/_singles/kairo.mp3,
which will end up as the filename argument in FileInfo's __init__ method.

Every class instance has a built−in attribute, __class__, which is the object's class. (Note that the
representation of this includes the physical address of the instance on my machine; your representation will be
different.) Java programmers may be familiar with the Class class, which contains methods like getName
and getSuperclass to get metadata information about an object. In Python, this kind of metadata is
available directly on the object itself through attributes like __class__, __name__, and __bases__.

You can access the instance's doc string just as with a function or a module. All instances of a class share
the same doc string.

Remember when the __init__ method assigned its filename argument to self["name"]? Well, here's
the result. The arguments you pass when you create the class instance get sent right along to the __init__
method (along with the object reference, self, which Python adds for free).


By creating the Point class, we created a new type, also called Point. The members of this type are called instances of the type or objects.

Creating a new instance is called instantiation, and is accomplished by calling the class.

Classes, like functions, are callable, and we instantiate a Point object by calling the Point class:

>>> class Point:
pass

>>> class Point:
"Point class for storing mathematical points."


>>> type(Point)
<class 'type'>
>>> p = Point()
>>> type(p)
<class '__main__.Point'>
>>>