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 :)
I wrote about the solutions to some problems I found from programming and data analytics. They may help you on your work. Thank you.
ezoic
Subscribe to:
Post Comments (Atom)
looking for a man
I am a mid aged woman. I was born in 1980. I do not have any kid. no complicated dating before . I am looking for a man here for marriage...
-
I tried to commit script to bitbucket using sourcetree. I first cloned from bitbucket using SSH, and I got an error, "authentication ...
-
https://github.com/boto/boto3/issues/134 import boto3 import botocore client = boto3.client('s3') result = client.list_obje...
-
Previously, I wanted to install "script" on Atom to run PHP. And there was some problem, like the firewall. So I tried atom-runner...
No comments:
Post a Comment