First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Classes and objects in Python

Classes, objects, attributes, methods, constructors, self, class vs instance variables, method types, properties, object identity, copying, and basic object design in Python.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers model real-world entities (sensor, user, invoice, motor) as software objects. Classes and objects help you organize code, bundle data with behavior, and make programs easier to extend, test and maintain.

Key ideas

  • Definition: An object (or instance) is a concrete occurrence created from a class; it has its own attribute values and can call the class’s methods.
  • Definition: An attribute is a named variable that belongs to a class or an object. If it belongs to an object, it is an instance attribute; if it belongs to the class itself, it is a class attribute (class variable).
  • Definition: A method is a function defined inside a class that operates on the class or its objects.
  • Definition: The constructor in Python is the special method __init__(self, ...) that runs automatically after a new object is created, to initialize the object’s attributes. Technically, object creation happens in __new__; __init__ is an initializer that sets up the new object.
  • Definition: self is the first parameter of an instance method; it refers to the current object on which the method is called. By convention the name is self, but any valid identifier can be used.
  • Definition: Encapsulation is the bundling of data (attributes) and operations (methods) inside a single unit (class), and controlling access to that data.
  • Definition: Class variable (class attribute) is a variable defined in the class body and shared by all instances of the class unless shadowed by an instance attribute of the same name.
  • Definition: Instance variable (instance attribute) is a variable attached to a specific object, usually set in __init__ as self.name = value.
  • Definition: A property is a managed attribute defined with @property and optional setter/deleter, providing controlled access while using attribute syntax (e.g., obj.x).
  • Definition: staticmethod is a method defined with @staticmethod that does not take self or cls; it behaves like a plain function placed in the class for logical grouping.
  • Definition: classmethod is a method defined with @classmethod whose first parameter is cls (the class); it can access/modify class state and can be used as an alternate constructor.
  • Definition: Object identity is the unique identity of an object in memory, returned by id(obj). Two variables can refer to the same object (same identity) or to equal but distinct objects.
  • Definition: Shallow copy creates a new object but does not recursively copy nested objects; references to nested objects are shared. Deep copy recursively copies nested objects, producing independent copies. In Python, use copy.copy for shallow and copy.deepcopy for deep copy.

Exact statements commonly used in exams:

  • Statement: In Python, “Everything is an object.” That means values such as integers, strings, lists, functions, and classes themselves are objects with identity, type, and value.
  • Statement: Attribute lookup order for an instance obj is: Python first searches the instance’s __dict__, then the class’s __dict__, then base classes (method resolution order). Assumption: simple single inheritance class; full details of MRO are part of inheritance topic. Note: Data descriptors (e.g., @property) defined on the class are checked before the instance’s __dict__, so a property can control access even if an instance attribute of the same name exists.
  • Statement: Name-mangling rule: An identifier of the form __name inside a class is transformed to _ClassName__name to reduce accidental access from outside; it is a convention-based privacy aid, not absolute security.
  • Statement: Parameter passing model: Python uses “pass-by-assignment” (also called “call-by-object-reference”). The function receives references to objects; re-binding a parameter does not affect the caller’s variable, but mutating a mutable object does.

Typical diagram to draw and label (describe in words):

  • Draw a UML-like class diagram box with three compartments, labeled top to bottom: “Class: BankAccount”, “Attributes: owner: str, balance: float, bank_name: str (class)”, “Methods: init(owner, balance), deposit(amount), withdraw(amount), get_balance()”. Mark bank_name with “class variable (shared)”. Then, draw two object boxes labeled “acc1: BankAccount” and “acc2: BankAccount”, each showing its own owner and balance values. Draw an arrow from each object to the class box to indicate they are instances of the class. Finally, annotate that both share bank_name while having different balance.

Building from first principles (step-by-step reasoning commonly examined):

  1. Identify the entity to model (e.g., Student). List its data (name, roll_no, marks) and behaviors (compute percentage, print details).
  2. Decide which data should be per object (instance variables) vs shared (class variables such as grading_scale or university_name).
  3. Define the class with class ClassName: and write __init__ to initialize instance variables using self.
  4. Write instance methods that use self to access/modify the object’s state.
  5. If needed, write @classmethod for alternate constructors or class-wide operations, and @staticmethod for related helper functions.
  6. Provide __str__ or __repr__ to get readable string forms for printing and debugging.
  7. Protect invariants (rules that must always be true) using properties or validation (e.g., balance cannot be negative unless allowed by overdraft). State the invariant explicitly.
  8. Test with multiple objects to ensure class variables are shared and instance variables are independent.

Important conventions and access control in Python:

  • Python does not enforce private attributes like some languages. Conventions:
    • Single underscore _name: internal use by convention.
    • Double underscore __name: triggers name-mangling to discourage external access.
    • Public attributes have no leading underscore.
  • Properties provide controlled access without changing the external interface: convert obj.get_x()/set_x(v) to obj.x and obj.x = v using @property and @x.setter.

Memory model in brief (practical exam level):

  • id(obj) shows identity. The is operator checks identity; == checks value equality via __eq__.
  • Mutability: Lists, dicts, sets, and user-defined objects are mutable by default; ints, floats, strings, tuples are immutable. Modifying a mutable attribute inside a method affects the object visible to callers.

Where to find related knowledge:

  • If you need loops or decisions inside methods, see the topics: “Decision control statements” and “Loops: while, for, break, continue and pass”. For organizing multi-file projects, see “Modules, packages and the standard library”. For OOP beyond classes/objects, see “Object-oriented programming concepts” and “Inheritance and polymorphism in Python”.

Formulas

  • def __init__(self, …): — Constructor to initialize instance attributes.
  • self.name = value — Set an instance attribute.
  • obj = ClassName(args) — Create an object (instantiate the class).
  • obj.method(args) — Call an instance method; Python passes self automatically.
  • ClassName.class_var = value — Define/modify a class variable.
  • @classmethod then def func(cls, …): — Define a class method; use cls for class-level operations.
  • @staticmethod then def func(…): — Define a static method; no self or cls parameter.
  • @property then def name(self): — Getter for a computed/validated attribute.
  • @name.setter then def name(self, value): — Setter with validation.
  • def __str__(self): — Human-friendly string; used by print(obj).
  • def __repr__(self): — Unambiguous string for debugging or recreation.
  • def __del__(self): — Destructor hook; called when the object is about to be garbage-collected. Its timing is not guaranteed, so avoid relying on it for critical resource management.
  • hasattr(obj, 'attr'), getattr(obj, 'attr', default), setattr(obj, 'attr', value), delattr(obj, 'attr') — Reflective attribute operations.
  • isinstance(obj, ClassName) — Type/instance check.
  • id(obj), obj.__dict__ — Inspect identity and instance namespace (unless __slots__ is used).

Worked examples

Example 1: Rectangle — instance attributes, methods, and __str__ Complete program:

class Rectangle:
    def __init__(self, length, width):
        if length <= 0 or width <= 0:
            raise ValueError("Length and width must be positive")
        self.length = float(length)
        self.width = float(width)

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

    def __str__(self):
        return f"Rectangle({self.length} × {self.width})"

# Read inputs: length and width
l = float(input())
w = float(input())
rect = Rectangle(l, w)
print(rect)
print(f"Area = {rect.area()}")
print(f"Perimeter = {rect.perimeter()}")

Sample input:

5
3

Exact output:

Rectangle(5.0 × 3.0)
Area = 15.0
Perimeter = 16.0

Example 2: BankAccount — class variable vs instance variable, property, and validation Complete program:

class BankAccount:
    bank_name = "ABC Bank"  # class variable shared by all accounts
    total_accounts = 0       # class variable counting instances

    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self._balance = float(balance)
        if self._balance < 0:
            raise ValueError("Initial balance cannot be negative")
        BankAccount.total_accounts += 1

    @property
    def balance(self):
        return self._balance

    @balance.setter
    def balance(self, amount):
        if amount < 0:
            raise ValueError("Balance cannot be negative")
        self._balance = float(amount)

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += float(amount)

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("Withdrawal must be positive")
        if amount > self._balance:
            raise ValueError("Insufficient funds")
        self._balance -= float(amount)

    @classmethod
    def from_string(cls, s):
        # Alternate constructor: "owner,balance"
        owner, bal = s.split(",")
        return cls(owner.strip(), float(bal))

    @staticmethod
    def rupees_to_paise(amount):
        # helper utility logically related to accounts
        return int(round(float(amount) * 100))

# Inputs: owner, initial balance, deposit, withdrawal
owner = input().strip()
init_bal = float(input())
dep = float(input())
wd = float(input())

acc = BankAccount(owner, init_bal)
acc.deposit(dep)
try:
    acc.withdraw(wd)
    print(f"{acc.owner} @ {acc.bank_name} => Balance: {acc.balance}")
except ValueError as e:
    print(f"Transaction failed: {e}")

print(f"Accounts created so far: {BankAccount.total_accounts}")
print(BankAccount.rupees_to_paise(acc.balance))

Sample input:

Priya
1000
250
400

Exact output:

Priya @ ABC Bank => Balance: 850.0
Accounts created so far: 1
85000

Example 3: Student — alternate constructor, isinstance, and computed percentage Complete program:

class Student:
    university = "XYZ University"

    def __init__(self, name, roll_no, total_marks, obtained):
        self.name = name
        self.roll_no = int(roll_no)
        self.total_marks = float(total_marks)
        self.obtained = float(obtained)
        if self.total_marks <= 0:
            raise ValueError("Total marks must be positive")
        if not (0 <= self.obtained <= self.total_marks):
            raise ValueError("Obtained marks must be in [0, total_marks]")

    @property
    def percentage(self):
        return (self.obtained / self.total_marks) * 100.0

    @classmethod
    def from_csv(cls, csv_line):
        # Format: name,roll_no,total,obtained
        name, r, t, o = [x.strip() for x in csv_line.split(',')]
        return cls(name, int(r), float(t), float(o))

    def __repr__(self):
        return (f"Student(name={self.name!r}, roll_no={self.roll_no}, "
                f"total={self.total_marks}, obtained={self.obtained})")

# Inputs: CSV line for a student
line = input()
stu = Student.from_csv(line)
print(isinstance(stu, Student))
print(stu.university)
print(f"{stu.name} ({stu.roll_no}) -> {stu.percentage:.2f}%")
print(repr(stu))

Sample input:

Aman, 42, 500, 440

Exact output:

True
XYZ University
Aman (42) -> 88.00%
Student(name='Aman', roll_no=42, total=500.0, obtained=440.0)

Common mistakes

  • Assigning to a name in __init__ without self., which creates a local variable instead of an instance attribute.
  • Misusing class variables: setting self.class_var = ... inside an instance method creates/overrides an instance attribute and does not change the class variable for other instances.
  • Using mutable default arguments in __init__ (e.g., def __init__(self, items=[])), causing instances to share the same list. Correct pattern: default to None, then set self.items = [] if items is None else list(items).
  • Confusing is (identity) with == (equality). Use == for value comparison.
  • Access control misunderstanding: believing __private makes attributes truly private. It only name-mangles; attributes can still be accessed as _Class__private if you know the name.
  • Not validating inputs in constructors and setters, leading to broken invariants (e.g., negative balances).
  • Forgetting to convert types when reading from input (strings vs numbers), causing logic errors or exceptions.
  • Omitting __str__/__repr__, leading to unreadable outputs like <MyClass object at 0x...> in exam outputs.

For your exam

  • Short notes: explain __init__, __str__ vs __repr__, attribute lookup order, name-mangling, pass-by-assignment with a small example. Include 3–4 bullet points and a 3–5 line code snippet.
  • Programs: implement a class with at least two instance methods, one class variable, input reading, and correct formatted output. Add validation and a demonstration of object creation and method calling. Outputs must exactly match the sample.
  • Diagrams: UML-style class diagram for a simple class showing attributes and methods, plus two instance objects showing different instance attribute values and a shared class attribute. Label clearly as described earlier.
  • Reasoning/Design: given an English description (e.g., “model a Library Book”), identify attributes (title, author, isbn, status) and methods (issue, return, is_available), choose which are instance vs class-level, state invariants (e.g., copies_available ≥ 0), and justify use of property for controlled update.
  • Pitfalls question: explain with example why mutable default arguments are dangerous, and show the correct pattern.

A full-marks answer usually includes: correct definitions, correct Python syntax, clear code with self, correct use of class vs instance variables, a brief justification of design choices, exact outputs, and, where asked, a labeled diagram description.

Quick check

  1. What is the difference between a class variable and an instance variable? Give one line of code for each.
  2. Why do we use @property and how does it change how we access an attribute?
  3. In Python, what is passed to an instance method as the first argument when you call obj.m(5)?

Answers: 1) Class variable belongs to the class and is shared by all instances (e.g., ClassName.count = 0); instance variable belongs to a specific object (e.g., self.name = "Asha" in __init__). 2) @property turns a method into a managed attribute so you can write obj.x and obj.x = v (with a setter) while running validation or computation internally. 3) The object itself is passed as the first argument, bound to the parameter self.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?