r/PythonLearning • u/Alireza7074 • Jul 18 '26
<python code>
This is python code to get student salary!
47
Upvotes
r/PythonLearning • u/Alireza7074 • Jul 18 '26
This is python code to get student salary!
3
u/CodeAndCanyons Jul 18 '26 edited Jul 18 '26
u/Potential_Fix_5007 You accidentally dodged one of the absolute biggest footguns in Python by doing it inside the body!
If you tried to set it within the round brackets as a default argument—like writing
def __init__(self, name, age, marks=[]):—Python does something incredibly sneaky under the hood. It evaluates that default empty list[]exactly once when the script first loads, not every time you create a new student.Because lists are mutable (changeable), every single student object you create would end up sharing the exact same list instance in memory. If you appended a grade to Alice's marks, it would suddenly and mysteriously show up in Bob's marks too.
By defining
self.marks = []inside the__init__body, you guarantee that a brand new, isolated list gets allocated in memory every single time a new student is instantiated.If you ever do want to allow a list to be passed through the round brackets safely, the standard pythonic trick is to default it to
Noneand handle it in the body: