Python Tutorial

Python Classes and Objects

Beginner-friendly guide to python classes and objects explaining class definition, __init__ constructor, self, methods, and variables with example code.

Drake Nguyen

Founder · System Architect

3 min read
Python Classes and Objects
Python Classes and Objects

Introduction to python classes and objects

Python supports object oriented programming in python, and python classes and objects are the foundation of that approach. A class acts as a blueprint that defines attributes and behaviors, while an object is a concrete instance created from that blueprint. This guide explains python class definition, how to create objects in python, and the role of constructors, methods, and variables with clear examples.

Simple python class declaration

A minimal class declaration uses the class keyword followed by the class name and a colon. Inside you can declare python class variables, methods, and a constructor.

class Vehicle:
    # class variables and method definitions go here
    pass

Example: defining a class and creating objects

Below is a practical python class and object example that demonstrates how to define instance variables via the constructor and how to call class methods.

class Person:
    # class variable shared by all instances
    species = "Homo sapiens"

    def __init__(self, name, age):
        # instance variables unique to each object
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

# create objects (instances) from the class
alice = Person("Alice", 30)
bob = Person("Bob", 25)

# call methods on the objects
alice.greet()
bob.greet()

python class constructor: __init__ and self

The python __init__ constructor initializes a new object when it is created. The first parameter of instance methods, including __init__, is conventionally named self; it refers to the specific instance. Use __init__ to set instance variables and prepare any needed state for the object.

Instance variables vs class variables

Understand the difference between attributes stored per instance and those shared across all instances:

  • Instance variables (also called instance attributes): defined inside methods (usually __init__) using self. Each object gets its own copy.
  • Class variables: declared directly in the class body. They are shared by every object of that class unless overridden on an instance.
class Counter:
    total = 0  # class variable

    def __init__(self):
        self.count = 0  # instance variable

    def increment(self):
        self.count += 1
        Counter.total += 1

Defining python class methods

Methods are functions defined inside the class body. An instance method receives self automatically. There are also class methods and static methods, but instance methods are the most common for object behavior.

class MathBox:
    def add(self, a, b):
        return a + b

    def scale(self, value, factor=2):
        return value * factor

How to create an object in python

To create an object, call the class name with any required constructor arguments. The expression returns an instance you can assign to a variable and use to access attributes and methods.

obj = Person("Charlie", 40)
print(obj.name)       # access instance variable
print(Person.species) # access class variable

Difference between class and object in python

  • Class: a template that defines properties and behaviors (attributes and methods). See python class definition.
  • Object: an instance created from a class; it has concrete values for instance variables.

Best practices and common pitfalls

  • Name classes with CapitalizedWords (PascalCase) to follow Python style conventions.
  • Always include self as the first parameter for instance methods.
  • Avoid using mutable objects as default argument values in methods.
  • Prefer clear separation between instance and class variables to prevent unexpected shared state.

Further learning and next steps

Once you are comfortable with python classes and objects, explore inheritance, polymorphism, and special methods (dunder methods) to build more advanced object oriented programming in python. Practice with small projects and examine the official Python documentation for classes to deepen your understanding.

Reference: Python official tutorial on classes (see docs.python.org) for authoritative details and examples.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.