AdjunctProfessorFalcon
AdjunctProfessorFalcon

Reputation: 1840

understanding instance object in reference to self convention in __init__(self) function when defining class

New to Python, trying to understand exactly what the self in the __init_(self) function is referring to.

A few tutorials I'm working with describe self as

referring to the instance whose method was called.

Which is not exactly a trivial statement for someone new to OOP.

I've been reading a lot about the whole backstory as to why you have to actually include an explicit self in Python, but need a simple explanation as to what it means to say that self is used to refer to the instance object ——> Does that mean that self is actually referring to the object that is the class itself you've just created? In other words, self somehow "boots up" the class in memory as an object?

Upvotes: 3

Views: 2171

Answers (7)

sw123456
sw123456

Reputation: 3459

When objects are instantiated, the object itself is passed into the self parameter.

enter image description here

Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.

enter image description here

EDIT (due to further question: Could you explain why exactly when objects are instantiated, the object itself is passed into the self parameter?)

The Object is passed into the self parameter so that the object can keep hold of its own data.

Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as a general template and would not be referenced to (belong to) the object. So by passing the object's name into the self parameter it means that if 100 objects are instantiated from the one class, they can all keep track of their own data and methods.

See the illustration below:

enter image description here

Upvotes: 1

o11c
o11c

Reputation: 16036

Behind the scenes, object construction is actually quite complicated.

Classes are objects too, and the type of a class is type (or a subclass, if using metaclasses). type has a __call__ method that is responsible for constructing instances. It works something like:

class type:
    def __call__(cls, *args, **kwargs):
        self = cls.__new__(cls, *args, **kwargs)
        if isinstance(self, cls):
            cls.__init__(self, *args, **kwargs)

Note, the above is for demonstrative purposes only.

Remember that, if a function is not defined on a class itself, it is looked up on its parent (as controlled by the mro), and usually.

Ultimately, __new__ must either call object.__new__(cls) to allocate a new instance of a class cls, or else return an existing object. If the existing object is of a different class, __init__ will not be called. Note that if it returns an existing object of the right class (or a subclass), __init__ will be called more than once. For such classes, all of the work is usually done in __new__.

Chances are you'll never use any of this, but it might help you understand what's going on behind the scenes.

Upvotes: 1

mitghi
mitghi

Reputation: 919

You can look at 'self' as referrer or a pointer to class internals which with that you can invoke methods or add/remove/update/delete attributes . Class is somehow an isolated object which has its own representation of data given to it . So basically , self is only explicitly defined as an argument, which with using that you can get access to class internals . Some programming languages does not explicitly include the keyword self. or some uses this ( like C ++ ) . take a look here:

a = 1
b = 2

class test(object):
    def __init__(self,a,b):
        self.a = a + 1
        self.b = b + 1

    def show_internals(self):
        print self.a, '\t', self.b

    def change_internals(self,a,b):
        self.a = a
        self.b = b

_my_class = test(3,4)

print a , b

_my_class.show_internals()

_my_class.change_internals(5,6)

_my_class.show_internals()

print a , b

the result is :

1 2

4 5

5 6

1 2

As you can see, with using self you can manipulate the data within the object itself. Otherwise you would end up editing global variables.

Upvotes: 0

DrBwts
DrBwts

Reputation: 3657

Simply, it means you are referring to a method or variable that is local to the object.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599480

Your second-last sentence is correct, but the last sentence is not. It has nothing to do with "booting up" or creating the object at all - the object already exists by that point.

I think you are missing the fact that self is used in all methods, not just __init__, to refer to the specific object that the method belongs to.

For instance, if you had a simple object with a name property, and a method called print_name, it might look like this:

def print_name(self):
    print(self.name)

So here the method is using self to refer to the properties of the object it has been called on.

Upvotes: 2

James
James

Reputation: 1238

When you write myClass(), python first creates an instance of your class, then immediately calls __init__() passing this object as the argument. self is a defined object in memory by the time you call __init__().

Upvotes: 1

Jacques de Hooge
Jacques de Hooge

Reputation: 6990

Every member function of a class, including the constructor (__init__) is invoked for a certain instance (object) of that class. Member functions have to be able to access the object for which they are called.

So e.g. in a.f(), f() has to have acces to a. In f, defined as f (this), this refers to a. The special thing for a constructor is that there is no object "before the dot" yet, because precisely that object is being constructed. So this refers to the object "just being constructed" in that case.

Upvotes: 1

Related Questions