Python OOP and typing · Concept
Class attributes, instance attributes, classmethod and staticmethod
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
What's the difference between a class attribute and an instance attribute? And between a normal method, a @classmethod and a @staticmethod? When do you use each?
Then
Follow-ups the interviewer asks next
- What's the difference between
__init__and__new__? - Why are alternate constructors written as classmethods?
- What does a name with two leading underscores (
__x) do? - What's in
obj.__dict__, and what's intype(obj).__dict__?
The answer
What a strong answer covers
- Instance attributes live in each object's
__dict__; class attributes live on the class and are shared. - Lookup goes instance, then class, then base classes (the MRO). Assigning through
selfcreates an instance attribute that hides the class one; mutating a mutable class attribute throughselfchanges it for everyone. - A normal method gets
self; a classmethod getscls, soOrder.from_row(row)works for subclasses too; a staticmethod is a plain function kept in the class namespace. __new__creates the object;__init__sets it up._xis "private" by convention;__xis name-mangled to_ClassName__xto avoid clashes in subclasses, not for security.
The red pen
Common traps
Avoid:a list as a class attribute "as a default"; thinking __x makes something truly private.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.