Q:

What is self in Python?

0

What is self in Python?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Interview Questions and Answers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is pep 8 in Python?... >>
<< Is indentation required in python?...