ARTICLE AD BOX
I am learning OOP in Python. I created a class and tried to update an instance variable inside a method, but the value doesn’t change.
class Student: def __init__(self, name, marks): self.name = name self.marks = marks def update_marks(self, value): marks = value # not updating self.marks ? s = Student("Shivam", 80) s.update_marks(95) print(s.marks) # still prints 80New contributor
Shivam Gupta is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
When you execute marks = value, you are only creating and initializing a variable that is local to your update_marks method; you are not updating the instance's marks attribute, which is accessed via the method's self argument:
... def update_marks(self, value): self.marks = value # not updating self.marks ?45.7k4 gold badges46 silver badges74 bronze badges
Explore related questions
See similar questions with these tags.
