Skip to content

Latest commit

 

History

History
52 lines (25 loc) · 2.6 KB

File metadata and controls

52 lines (25 loc) · 2.6 KB

Practice Questions & Solutions — Classes & Objects

📝

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.

Q1. What do __init__ and self do?

  • 💡 Solution & explanation

    Answer: __init__ is the constructor, run automatically when you create an instance, used to set up initial attributes. self is the reference to the current instance, passed automatically as the first parameter of every instance method.

    Explanation: Dog("Rex") calls __init__(self, "Rex"); inside it self.name = name stores data on that specific object.

Q2. What's the difference between an instance attribute and a class attribute?

  • 💡 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.

Q3. What do the dunder methods __str__, __len__, and __eq__ let you customize?

  • 💡 Solution & explanation

    Answer: __str__ → what print(obj)/str(obj) shows; __len__ → what len(obj) returns; __eq__ → how obj1 == obj2 is 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__.

Q4. What do getattr, setattr, and hasattr do?

  • 💡 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 (returns True/False).

    Explanation: They let you work with attribute names as strings — useful for dynamic/configurable code. dir(obj) lists available names; delattr removes one.

Q5. In obj.method(), what is the difference between an attribute and a method?

  • 💡 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 as obj.method()).

    Explanation: Dot notation accesses both; the parentheses are what call a method. A method always receives the instance as self automatically.