Reading history

Python Classes and Objects: __init__, self and Methods

4 min read 2 views

Learn Python classes and objects: defining a class, __init__ and self, instance vs class attributes, methods, __str__ and common OOP mistakes.

A class is a blueprint, and an object is a thing built from it. A Student class describes what every student has (a name, marks) and can do (work out a grade); each actual student is an object with its own values. Classes let you keep data and the functions that work on it together, which is the core idea of object-oriented programming (OOP).

In this lesson you will learn

  • How to define a class and create objects from it
  • What __init__ and self do
  • The difference between instance and class attributes
  • How to write methods, including __str__
  • How objects keep their own separate state

Your First Class

class Student:
    school = "Core Tech ED"          # class attribute, shared by all

    def __init__(self, name, marks):
        self.name = name             # instance attributes
        self.marks = marks

    def grade(self):
        if self.marks >= 80:
            return "A"
        if self.marks >= 60:
            return "B"
        return "C"

    def __str__(self):
        return f"{self.name} ({self.marks})"

s1 = Student("Rafi", 85)
s2 = Student("Nila", 64)

print(s1.name, s1.grade())
print(s2, s2.grade())
print(s1.school, s2.school)
print(isinstance(s1, Student))

Output

Rafi A
Nila (64) B
Core Tech ED Core Tech ED
True
  • class Student: defines the blueprint. By convention, class names use CapitalisedWords.
  • __init__ runs automatically when you create an object with Student("Rafi", 85). It sets up the object’s starting values.
  • self is the object being worked on. self.name = name stores the name on that object. Python passes self for you; you never write it in the call.
  • Instance attributes (name, marks) belong to one object. The class attribute school is shared by every object.
  • __str__ controls what print(obj) shows. Without it you would see something like <Student object at 0x...>.

Objects Keep Their Own State

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        self.history = []

    def deposit(self, amount):
        self.balance += amount
        self.history.append(("deposit", amount))
        return self                      # allows chaining

    def withdraw(self, amount):
        if amount > self.balance:
            print("Not enough balance")
            return self
        self.balance -= amount
        self.history.append(("withdraw", amount))
        return self

acc = BankAccount("Tania", 500)
acc.deposit(200).withdraw(100).withdraw(900)
print(acc.balance)
print(acc.history)

other = BankAccount("Arif")
print(other.balance, len(other.history))

Output

Not enough balance
600
[('deposit', 200), ('withdraw', 100)]
0 0

Each account has its own balance and history. Changing Tania’s account does not touch Arif’s. The methods return self, so calls can be chained on one line. The failed withdrawal of 900 printed a message and left the balance unchanged.

Do not use a list as a class attribute for per-object data

If history = [] were written at class level, every account would share the same list. Create mutable values inside __init__ so each object gets its own.

Key OOP Terms

TermMeaning
ClassThe blueprint: class BankAccount:
Object / instanceOne thing made from the class: acc = BankAccount("Tania")
AttributeData stored on an object: acc.balance
MethodA function defined in the class: acc.deposit(200)
Constructor__init__, which sets up a new object

Common Mistakes

  1. Forgetting self as the first parameter of a method, which gives “takes 0 positional arguments but 1 was given”.
  2. Writing name = name instead of self.name = name, so the value is never stored on the object.
  3. Calling the class without arguments when __init__ requires them.
  4. Misspelling __init__ with single underscores, so it never runs.

Practice Exercises

Exercise 1. Write a Rectangle class with width, height and an area() method.

Show answer
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

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

print(Rectangle(3, 4).area())   # 12

Exercise 2. Add a class attribute count to Student that goes up every time a student is created.

Show answer

Add count = 0 at class level and Student.count += 1 inside __init__.

Frequently Asked Questions

Is self a keyword in Python?

No, it is just the conventional name for the first parameter of a method. Any name would work, but always use self so others can read your code.

What is the difference between __str__ and __repr__?

__str__ is the friendly text for users and print(). __repr__ is the detailed text for developers, shown in the interactive shell and inside lists.

Is everything in Python an object?

Yes. Numbers, strings, lists and even functions and classes are objects with their own types and methods.

Summary

  • A class is a blueprint; an object is one instance of it.
  • __init__ sets up each new object, and self refers to that object.
  • Instance attributes are per object; class attributes are shared.
  • __str__ controls how an object prints.

Next: reuse a class’s code with Python Inheritance.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *