Skip to content
AL-306 · Computer Workshop/Introduction to Python-I/Quick Revision Short Notes

Computer Workshop/Introduction to Python-I (AL-306) - Unit 4 Short Notes

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.

  1. A class is defined with the class keyword and its body is indented.
  2. An object is created by calling the class, for example s = Student("Ravi").
  3. Many objects can be made from one class, and each has its own data.
  4. __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.

  1. Instance attributes are set through self inside __init__ and are separate for every object.
  2. Class attributes are written in the class body and are shared by all objects (college above).
  3. Attributes are read with dot notation, obj.name, and can be added or changed at run time.
  4. 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.

  1. The first parameter of an instance method is self, which refers to the calling object.
  2. obj.show() is treated by Python as Student.show(obj), so self is passed automatically.
  3. Methods read and change instance attributes through self.
  4. @classmethod takes cls and @staticmethod takes neither self nor cls.

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

  1. Python searches names by the LEGB rule: Local, Enclosing, Global, then Built-in.
  2. Local names live inside a function, global names at module level, and built-in names such as len are always available.
  3. A class has its own namespace, and instance attributes live in the object's namespace.
  4. The global and nonlocal keywords 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.

  1. Syntax is class Child(Parent):, and the child gets all parent members.
  2. super().__init__() calls the parent constructor from the child.
  3. Types are single, multiple, multilevel, hierarchical and hybrid inheritance.
  4. 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.

  1. Python has no true method overloading: a second def with the same name replaces the first.
  2. Default arguments or *args imitate overloading.
  3. Operator overloading is done with special methods such as __add__, __sub__, __eq__ and __str__.
  4. a + b on objects then calls a.__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.

  1. The child method must have the same name and normally the same parameters.
  2. The call is decided by the object's class, so a child object runs the child version.
  3. super().method() can still call the parent version.
  4. 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.

  1. A name starting with a double underscore, such as __balance, is private to the class.
  2. Python mangles it to _ClassName__balance, so obj.__balance raises AttributeError.
  3. A single underscore, _x, is only a convention meaning "internal use".
  4. 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.

  1. Code that may fail goes in the try block, and the handler in except.
  2. Examples are ZeroDivisionError, ValueError, TypeError, IndexError and FileNotFoundError.
  3. An else block runs only if no exception occurred.
  4. raise throws 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.

  1. except ValueError: catches only that type, and several clauses can follow one try.
  2. except (TypeError, ValueError): catches any of a tuple of types.
  3. except Exception as e: stores the error object in e so its message can be printed.
  4. 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.

  1. It is used for clean-up such as closing files or releasing resources.
  2. It runs even if the try block returns or the exception is not handled.
  3. try can be written with only finally, without except.
  4. 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.

  1. Define it as class NegErr(Exception): pass.
  2. Throw it with raise NegErr("message").
  3. Catch it with except NegErr as e:, and e prints the message.
  4. 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.
  • self is 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.
  • __x is name-mangled to _Class__x and hides the data.
  • try / except / else / finally is the order of blocks.
  • finally always runs; raise throws 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.
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in