ezoic

Monday, January 23, 2017

Python class self

wiki:

https://en.wikipedia.org/wiki/This_(computer_programming)

quora:

https://www.quora.com/What-does-self-mean-in-python-class-Why-do-we-need-it







A class have methods. Also, a class can have multiple objects. Right? Now when any object calls a method of the class, how would the method know which object has called it?
For example, if any of your family member calls your name, how do you recognize that its your mother or father or brother, if you are sitting in a different room? You recognize the voice. Right?

Similarly, self represents the voice of the object.

Example -

class myClass:
    def __init__(self):
        self.x = []
        self.x.append(1)

    def print_x(self):
        print (self.x)

obj1 = myClass()
obj1.print_x()    # prints [1]

obj2 = myClass()
obj2.print_x()    # prints [1],  not "[ 1, 1]"


Now see, both the times [1] is printed even when we used "append".

Whenever you write - obj1.print_x(), self passes the instance of "obj1" . Now "print_x()" would know that "obj1" has called it. Therefore, obj1 would have its own copy of "x" not matter how many times method "print_x" is called by other objects. Same would be the case with obj2.

In other object oriented languages too, when you call a method using an object, instance of an object get passed automatically(like "this" pointer in C++), but we don't have to write that explicitly. Its just that in python you have to be explicit :)



No comments:

Post a Comment

looking for a man

 I am a mid aged woman. I live in southern california.  I was born in 1980. I do not have any kid. no compliacted dating.  I am looking for ...