__init__


#1

I'm a beginner, and I've been trying to wrap my head around classes. I've read things like "init is called automatically every time an instance object is created."

So is init defined explicitly in a class strictly on the occasions when we want each of our instance objects to have more variables? Does it exist only for that purpose?

`


#2

Hi @wrosen02 ,

The __init__ method can be designed to perform any actions that you would like to occur when a new instance object is created. In most cases, this would involve assigning values to variables that apply to that new instance. However, it could involve other actions, as well, such as incrementing a counter that keeps track of the total number of instances that have been instantiated for that class, or might involve printing something to the console. In fact, you do not have to set up any variables at all if you do not deem it necessary to do so. Just write the __init__ method to perform any actions that you decide are appropriate when a new instance is created.


#3

Thanks. Recently stumbled on this example:

class Point(object):
    def __init__(self,x = 0,y = 0):
        self.x = x
        self.y = y

    def distance(self):
        """Find distance from origin"""
        return (self.x**2 + self.y**2) ** 0.5

Why, in the parantheses of the init method, are x and y both given the specific value 0? Would this work if they weren't?


#4

As a default, yes, in case no parameters are given to a new instance. Consider,

a = Point()
print a.distance()    # 0.0

The point in geometry would be known as the Origin.

b = Point(3,4)
print b.distance()    # 5.0

#5

Thanks for the reply. So they are set to zero in case no parameters are given to a new instance. If they weren't:

class Point(object):
def init(self, x, y):
self.x = x
self.y = y

then creating a new instance b = Point(0, 0) and calling the distance method would give an identical result, right?

b = Point(0, 0)
print b.distance()

I guess I'm just confused why someone would create an instance with no parameters. Maybe I don't have enough experience.


#6

Also, and sorry for so many questions, but is it correct to say that what init does is assign locations in memory for each instance name and parameters as it is created?


#7

A class is like a function factory, in a way. When we instantiate a new object, it holds on to the values we give the initializer function. Those are the instance variables. We can also give the instances class variables and methods that allow each instance to manage them. Things like passwords, user names, game scores, etc. that we wouldn't want readily accessible can be shielded in class variables.

Think of each instance as a separate package with links to class methods that can look back at the package and execute in that context when called upon by the instance, hence, self.

It can happen, and the function is safe-guarded against it. But it could also be deliberate, as in the example above. A shortcut to the Origin.


#8

Supplement

Just to shed some light on factories, which are functions that return a function, or closures, consider the following:

def factory(c):
    def times(x):
        return c * x
    return times

by_4 = factory(4)

print by_4(8)    # 32

When the factory returned the times function, it had the constant 4 in tow. We have instantiated a classless object, in effect, but we could think of it as the Factory class in the loosest of terms.

Python also gives us a powerful tool for writing factories, anonymous functions called lambdas.

def factory(c):
    return lambda x: c * x

from math import pi
by_pi = factory(pi)

print by_pi(10)    # 31.4159265359

#9

In the sense that factory() contains times() in the same way that a class contains methods?


#10

The are loosely comparable, but it ends with that parallel. A factory returns a function with an encapsulated constant or set of constants that is built to serve a specific purpose. A class returns an instance object that has properties and methods, and it can be extended to have subclasses which may also be extended. Clealy a class has a much wider berth and range of uses. A factory is pretty much a utility so we shouldn't read too much into the analogy.


#11

I understand. Thanks a lot.


#12

Also, and I apologize if you answered this already, but is it correct to say that what __init__ does is assign locations in the computer memory to the instance name and variables when an object is instantiated?


#13

I'm just winging this answer, so take it with a grain of salt.

The initializer doesn't assign memory, the OS does that. Essentially, it creates the instance variables that are assigned to self. It would take a request from the compiler process to have memory allocated.

The OS would then map out the requested memory and return a stub to the process that points to the page in memory. Execution context and scope are managed by Python.


#14

Hi @wrosen02 ,

What @mtf says is correct. The __init__ method doesn't assign memory. In fact, if you design a class that has no __init__ method, you can still create an instance of that class.

In this example, Minimal_Class has no __init__ method, but we can create an instance of it anyway ...

# Minimal_Class.py
class Minimal_Class:
    def __str__(self):
        return "Instance of Minimal_Class"

mc = Minimal_Class()
print(mc)

Output ...

Instance of Minimal_Class

If a class does have an __init__ method, it will execute automatically when you instantiate the class. The purpose of an __init__ method is to perform any tasks that should be performed when an instance is created. It is up to the designer of the class to decide what those tasks are.

By the way, object has an __init__ method, so if you do this ...

class Minimal_Class(object):
    pass

... your class will inherit that default __init__ method.


#15

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.