self represents the instance of the class. In Python, this is explicitly included as the first parameter. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.
class human():
# init method or constructor
def __init__(self, gender, color):
self.gender = gender
self.color = color
def show(self):
print("Gender is", self.gender )
print("color is", self.color )
# both objects have different self which
# contain their attributes
amlendra = human("male", "white")
pooja = human("woman", "black")
amlendra.show()
pooja.show()
Output:
Gender is male color is white Gender is woman color is black
Answer :
self represents the instance of the class. In Python, this is explicitly included as the first parameter. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.
Output:
Gender is male
need an explanation for this answer? contact us directly to get an explanation for this answercolor is white
Gender is woman
color is black