Understanding 'self' In Python Classes



Understanding 'self' In Python Classes

Understanding 'self' In Python Classes

Understanding ‘self’ in Python Classes

In Python, when working with classes, ‘self’ is a conventionally used parameter that refers to the instance of the class itself. It allows us to access and modify the object’s attributes within class methods.

Here’s a basic class called ‘MyClass.’ We have an initializer method, init, which is automatically called when we create an instance of the class. It takes two parameters: ‘self’ and ‘name.’

The ‘self’ parameter refers to the specific instance of the class. It’s like a reference that allows us to access and manipulate the object’s attributes. In this case, we assign the value of the ‘name’ parameter to the ‘name’ attribute of the object using self.name = name.

We create an instance of the ‘MyClass’ called ‘obj’ and provide the value “Example” for the ‘name’ parameter. As the __init__ method is automatically called during instantiation, the value of ‘name’ is assigned to the ‘name’ attribute of the ‘obj’ object. Now, if we access the ‘name’ attribute using obj.name, we’ll see that it returns the value “Example.”
—————-
Subscribe: 👉 https://bit.ly/3ysz8kc
——————–
Code here: 👉

class MyClass:
def __init__(self, name):
self.name = name

obj = MyClass(“Example”)
print(obj.name) # Output: “Example”

—————-

#python #self #coding

Comments are closed.