Practice set — covers SL No 44–48 (classes, __init__, self, attributes, methods, dunder methods & dynamic attribute handling). Answer each from memory before opening the solution.
-
💡 Solution & explanation
Answer:
__init__is the constructor, run automatically when you create an instance, used to set up initial attributes.selfis the reference to the current instance, passed automatically as the first parameter of every instance method.Explanation:
Dog("Rex")calls__init__(self, "Rex"); inside itself.name = namestores data on that specific object.
-
💡 Solution & explanation
Answer: An instance attribute (
self.x = ...) is unique to each object; a class attribute (defined directly in the class body) is shared by all instances.Explanation: Class attributes are good for constants/defaults. Beware mutable class attributes (like a shared list) — every instance would mutate the same object.
-
💡 Solution & explanation
Answer:
__str__→ whatprint(obj)/str(obj)shows;__len__→ whatlen(obj)returns;__eq__→ howobj1 == obj2is compared.Explanation: "Dunder" (double-underscore) methods hook your objects into Python's built-in syntax, making them behave like native types.
__repr__is the developer-facing twin of__str__.
-
💡 Solution & explanation
Answer:
getattr(obj, "x", default)reads an attribute by name (with optional fallback);setattr(obj, "x", val)sets one by name;hasattr(obj, "x")checks existence (returnsTrue/False).Explanation: They let you work with attribute names as strings — useful for dynamic/configurable code.
dir(obj)lists available names;delattrremoves one.
-
💡 Solution & explanation
Answer: An attribute is data stored on the object (accessed as
obj.name); a method is a function defined in the class that acts on the object (called asobj.method()).Explanation: Dot notation accesses both; the parentheses are what call a method. A method always receives the instance as
selfautomatically.