How unit 4 is examined
This unit covers classes, objects, attributes, methods, scopes, inheritance, overloading, overriding, data hiding and exception handling; no topic has been asked recently, so each is kept to its exam-ready core.
Class and Object
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. A class is a blueprint that defines the attributes and methods of a kind of thing; an object is an instance created from that class.
Key points.
- A class is defined with the
classkeyword and its body is indented. - An object is created by calling the class, for example
s = Student("Ravi"). - Many objects can be made from one class, and each has its own data.
__init__is the constructor and runs automatically when an object is created.
class Student:
college = "RGPV"
def __init__(self, name): self.name = name
def show(self): return self.name + " " + Student.college
print(Student("Ravi").show()) # Ravi RGPV
<mark>A class is a blueprint and an object is an instance of that blueprint.</mark>
Attributes
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. Attributes are the variables that belong to a class or to its objects; they hold the state of the object.
Key points.
- Instance attributes are set through
selfinside__init__and are separate for every object. - Class attributes are written in the class body and are shared by all objects (
collegeabove). - Attributes are read with dot notation,
obj.name, and can be added or changed at run time. - If an instance attribute is missing, Python looks for the class attribute of the same name.
<mark>Instance attributes belong to one object, class attributes are shared by all objects.</mark>
Methods
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. A method is a function defined inside a class that works on the object it is called on.
Key points.
- The first parameter of an instance method is
self, which refers to the calling object. obj.show()is treated by Python asStudent.show(obj), soselfis passed automatically.- Methods read and change instance attributes through
self. @classmethodtakesclsand@staticmethodtakes neitherselfnorcls.
<mark>self is the reference to the current object and is passed automatically as the first argument.</mark>
Scopes and Namespaces
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. A namespace is a mapping from names to objects; a scope is the region of the program where a name can be used directly.
Key points.
- Python searches names by the LEGB rule: Local, Enclosing, Global, then Built-in.
- Local names live inside a function, global names at module level, and built-in names such as
lenare always available. - A class has its own namespace, and instance attributes live in the object's namespace.
- The
globalandnonlocalkeywords let a function assign to an outer name.
<mark>Names are resolved in the order Local, Enclosing, Global, Built-in (LEGB).</mark>
Inheritance
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. Inheritance lets a child (derived) class acquire the attributes and methods of a parent (base) class, which promotes reuse.
Key points.
- Syntax is
class Child(Parent):, and the child gets all parent members. super().__init__()calls the parent constructor from the child.- Types are single, multiple, multilevel, hierarchical and hybrid inheritance.
- Python allows multiple parents, and the method lookup follows the MRO (method resolution order).
<mark>Inheritance lets a derived class reuse and extend the members of a base class.</mark>
Overloading
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. Overloading gives one name or operator different behaviour depending on its operands.
Key points.
- Python has no true method overloading: a second
defwith the same name replaces the first. - Default arguments or
*argsimitate overloading. - Operator overloading is done with special methods such as
__add__,__sub__,__eq__and__str__. a + bon objects then callsa.__add__(b).
class V:
def __init__(s, x): s.x = x
def __add__(s, o): return V(s.x + o.x)
print((V(2) + V(3)).x) # 5
<mark>Operator overloading redefines an operator for user classes through special methods like add.</mark>
Overriding
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. Overriding is when a child class defines a method with the same name as a parent method, replacing the parent version for child objects.
Key points.
- The child method must have the same name and normally the same parameters.
- The call is decided by the object's class, so a child object runs the child version.
super().method()can still call the parent version.- It gives run-time polymorphism.
class A:
def f(self): return "A"
class C(A):
def f(self): return "C"
print(A().f(), C().f()) # A C
<mark>Overriding redefines a parent method in the child class with the same name.</mark>
Data hiding
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. Data hiding (encapsulation) restricts direct access to an object's data so it can be changed only through its methods.
Key points.
- A name starting with a double underscore, such as
__balance, is private to the class. - Python mangles it to
_ClassName__balance, soobj.__balanceraisesAttributeError. - A single underscore,
_x, is only a convention meaning "internal use". - Getter and setter methods give controlled access and allow validation.
class P:
def __init__(s): s.__b = 5
# P().__b -> AttributeError; P()._P__b -> 5
<mark>A double-underscore name is name-mangled, which hides it from direct outside access.</mark>
Exception: Exception Handling
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. An exception is a run-time error that stops normal flow; exception handling catches it with try/except so the program continues.
Key points.
- Code that may fail goes in the
tryblock, and the handler inexcept. - Examples are
ZeroDivisionError,ValueError,TypeError,IndexErrorandFileNotFoundError. - An
elseblock runs only if no exception occurred. raisethrows an exception deliberately.
try: 1/0
except ZeroDivisionError: print("z") # z
<mark>try holds risky code and except handles the error so the program does not crash.</mark>
Except clause
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. The except clause is the handler that runs when the matching exception occurs in the try block.
Key points.
except ValueError:catches only that type, and several clauses can follow onetry.except (TypeError, ValueError):catches any of a tuple of types.except Exception as e:stores the error object ineso its message can be printed.- A bare
except:catches everything, which hides bugs and is discouraged.
<mark>An except clause catches a named exception type and runs its handler.</mark>
Try finally clause
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. The finally block always runs after try and except, whether or not an exception occurred.
Key points.
- It is used for clean-up such as closing files or releasing resources.
- It runs even if the
tryblock returns or the exception is not handled. trycan be written with onlyfinally, withoutexcept.- The order is
try,except,else,finally.
<mark>The finally block always executes, so it is used for guaranteed clean-up.</mark>
User Defined Exceptions
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. A user defined exception is a custom error class created by inheriting from Exception.
Key points.
- Define it as
class NegErr(Exception): pass. - Throw it with
raise NegErr("message"). - Catch it with
except NegErr as e:, andeprints the message. - It makes errors specific to the application, such as an invalid age.
class NegErr(Exception): pass
try: raise NegErr("neg")
except NegErr as e: print(e)
finally: print("done") # neg, then done
<mark>Custom exceptions are classes that inherit from Exception and are raised with raise.</mark>
Last-minute revision
- A class is a blueprint and an object is its instance;
__init__is the constructor. - Instance attributes are per object (
self.x); class attributes are shared. selfis the calling object, passed automatically as the first argument.- Name lookup follows LEGB: Local, Enclosing, Global, Built-in.
class Child(Parent):gives inheritance;super()reaches the parent.- Python has no true method overloading; operators are overloaded with
__add__and similar. - Overriding is the same method name redefined in the child class.
__xis name-mangled to_Class__xand hides the data.try/except/else/finallyis the order of blocks.finallyalways runs;raisethrows an exception.- A custom exception inherits from
Exception.
Memory hooks
- LEGB: "Look Every Good Book".
- TEEF: try, except, else, finally.
- Double underscore means hidden, single underscore means a polite request.
- Overload: same name, different operands; override: same name, child replaces parent.
Coverage checklist
- Class and Object: no past questions.
- Attributes: no past questions.
- Methods: no past questions.
- Scopes and Namespaces: no past questions.
- Inheritance: no past questions.
- Overloading: no past questions.
- Overriding: no past questions.
- Data hiding: no past questions.
- Exception: Exception Handling: no past questions.
- Except clause: no past questions.
- Try finally clause: no past questions.
- User Defined Exceptions: no past questions.