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 80
marks = value # not updating self.marks ?Yes, that's correct. What are you confused about? Did you just forget to typeself., or were you expectingmarks =to be equivalent toself.marks =? That's a perfectly reasonable assumption coming from other programming languages, it's just not how Python works. Please edit to clarify.self.marks = valueand you explain why, does it really matter if they forgot theself.or thought it was unnecessary? They will now know the complete story, so what is gained by making them edit the question just to confess their forgetfulness or ignorance? And whoever voted to close this question because it was either a typo or non-reproducible is doing the OP a disservice because it was a legitimate minimal reproducible example and only maybe was it a typo. I think the OP deserves an answer, which closing prevents.# not updating self.marks?it is pretty clear that they thought theself.was unnecessary.self.marks =in__init__, so they know that that's the correct way to do it in at least some contexts, but it's not clear why they thought different methods would allow different syntax.selfparameter? Why is it needed? The top answer is a little too brief, but Thomas Wouters's answer is better.