Creating Classes & Objects (Review)
Creating Classes & Objects (Review & Deep Dive)
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which bundle state (attributes/data) and behavior (methods/functions) together. In Python, everything is an object—from simple integers and strings to complex modules and custom classes.
1. Classes vs. Instances
A class serves as a blueprint or schema defining the attributes and operations that instances will possess. An instance (or object) is a concrete manifestation created in memory based on that blueprint.
2. The __init__ Constructor and self
The __init__ method is Python's initialization hook called immediately after an instance is created in memory:
self: A reference to the specific instance currently being initialized or manipulated. Python automatically passes the instance as the first argument when calling instance methods.
3. Instance Attributes vs. Class Attributes
Understanding the distinction between class-level and instance-level attributes is critical to avoiding state bugs:
- Instance Attributes: Bound to
self. Each instance maintains its own distinct copy in its__dict__. - Class Attributes: Defined directly inside the class body, shared across all instances of that class.
4. Instance, Class, and Static Methods
Python provides three distinct method types using decorators:
| Method Type | Decorator | First Argument | Typical Use Case |
|---|---|---|---|
| Instance Method | (None) | self | Manipulates individual instance state |
| Class Method | @classmethod | cls | Factory methods, modifying class-level state |
| Static Method | @staticmethod | (None) | Self-contained utility functions logically grouped in the class |
5. String Representations: __str__ vs __repr__
Every Python class should define informative string representations:
__str__: User-friendly, readable string representation (returned byprint(obj)orstr(obj)).__repr__: Unambiguous, developer-oriented string used for debugging (returned by typingobjin interactive shell orrepr(obj)). Ideally should look like valid Python code to recreate the object.
Multiple Choice Questions
1. What does the self parameter in a Python instance method represent?
A. The class type that spawned the method B. A pointer to the global Python execution namespace C. The specific instance on which the method was invoked D. A copy of Python's garbage collection registry Answer: C Explanation: When invoking an instance method like obj.method(), Python passes the instance obj automatically as the first parameter self.
2. What happens if you define a mutable list as a class attribute and append items to it from an instance?
A. Python throws an AttributeError B. The list is cloned exclusively for that instance C. The list is modified for all instances sharing that class D. The list converts automatically into an immutable tuple Answer: C Explanation: Class attributes are shared across all instances. Modifying a mutable class attribute affects every instance that references it.
3. Which decorator allows defining an alternative factory constructor that receives the class itself as cls?
A. @property B. @classmethod C. @staticmethod D. @factory Answer: B Explanation: @classmethod passes the class object as its first argument (usually named cls), allowing the method to construct and return new instances of that class or its subclasses.
4. How does @staticmethod differ from regular instance methods and class methods?
A. It cannot be called without first creating an instance B. It automatically runs in a background thread C. It does not receive an implicit first argument (self or cls) D. It can only return integer values Answer: C Explanation: A @staticmethod is a plain function bound into a class's namespace without receiving automatic self or cls references.
5. What is the standard purpose of the __repr__ special method in Python?
A. To print formatted HTML documents for web browsers B. To provide an unambiguous, developer-focused string representation of the object C. To serialize the object to binary byte streams D. To validate user permissions before accessing attributes Answer: B Explanation: __repr__ is intended for developers and debugging, providing an explicit, unambiguous representation of the object state.
Inheritance & Method Overriding
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Project: CSV Contact Manager | Inheritance & Method Overriding |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.