Python doesn’t have this keyword. Python has a self that represents the instance of the class. Use the “self” to access the attributes and methods of the class in python. It binds the attributes with the given arguments.
this, self, and Me are keywords used in computer programming languages to refer to the object, class, or other entity of which the currently running code is a part.
Python this keyword
Simple example code.
class food():
# init method or constructor
def __init__(self, fruit, color):
self.fruit = fruit
self.color = color
def show(self):
print("fruit is", self.fruit)
print("color is", self.color)
apple = food("apple", "red")
grapes = food("grapes", "green")
apple.show()
grapes.show()
Output:
Difference between Python self and Java this
Answer: Technically both self
and this
are used for the same thing. They are used to access the variable associated with the current instance. The only difference is, you have to include self explicitly as the first parameter to an instance method in Python, whereas this is not the case with Java. Moreover, the name self
can be anything. It’s not a keyword, as you already know. you can even change it to this
, and it will work fine. But people like to use self
, as it has now become a bit of a convention.
Here’s a simple instance method accessing an instance variable in both Python and Java:
Python:
class Circle(object):
def __init__(self, radius):
# declare and initialize an instance variable
self.radius = radius
# Create object. Notice how you are passing only a single argument.
# The object reference is implicitly bound to `self` parameter of `__init__` method
circle1 = Circle(5);
Java:
class Circle {
private int radius;
public Circle(int radius) {
this.radius = radius;
}
}
Circle circle1 = new Circle(5);
Source: https://stackoverflow.com/
Do comment if you have any doubts or suggestions on the Python keyword topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.