ThisCalculator

Everyday

Python Classes: Objects, Attributes, and Methods Explained

Updated · Standard formula, shown below

Python Classes: Objects, Attributes, and Methods Explained

Python classes define reusable kinds of objects: a class describes the data an object can hold and the actions it can perform. An object is a particular instance of a class, its attributes are values associated with it, and its methods are functions designed to work with it.

Why Python Has Classes

Classes help organize programs around related data and behavior. A program that tracks several books, for example, might store each book’s title and author alongside operations such as displaying its details. A class puts that shared structure in one definition, while each book is represented by a separate object with its own values.

Python itself uses objects extensively: strings, lists, dictionaries, functions, and classes are all objects. You can use many of them without defining a class. Classes are useful when a program needs its own meaningful type, especially when related values and operations belong together.

Class, Object, and Instance

A class is a definition; an object is a value created from that definition. The terms object and instance are often used interchangeably in beginner explanations. More precisely, an instance is an object whose type is a particular class.

class Book:
    pass

first = Book()
second = Book()

Book names a class. Calling it with parentheses creates an instance, so first and second refer to distinct objects. The pass statement is a placeholder that does nothing; it lets this minimal class definition run.

By convention, class names usually use CapWords, such as Book, while variables and methods usually use lowercase words with underscores, such as first_book and show_details.

Attributes: Data Attached to Objects

An attribute is a name accessed through an object or class, using dot notation. For instance, book.title reads an attribute named title from book. Attributes can hold strings, numbers, other objects, or many other kinds of values.

A common way to give each instance its own attributes is the special initialization method __init__:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

first = Book("The Left Hand of Darkness", "Ursula K. Le Guin")
print(first.title)

When Book(...) creates an instance, Python calls __init__ to initialize it. The supplied arguments are assigned to self.title and self.author. The final line prints the title. Technically, __init__ initializes an object that has already been created; it is not the method that creates the object.

self refers to the current instance. It is the conventional name for the first parameter of an instance method, not a special keyword: Python supplies the instance automatically when a method is called through it. Using self.title stores a value on that particular object. Omitting self or using a different name consistently can change behavior, but sticking to the convention makes code clear.

Methods: Behavior Belonging to a Class

A method is a function defined in a class. An instance method can read or change that instance’s attributes:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def describe(self):
        return f"{self.title} by {self.author}"

first = Book("The Left Hand of Darkness", "Ursula K. Le Guin")
print(first.describe())

Calling first.describe() passes first to the method as its self argument. The method then uses that object’s attributes and returns a string. A method can also accept other arguments, perform calculations, or update the instance. A method that returns a value does not automatically print it; use print if you want it displayed.

Python also supports class methods, marked with @classmethod, which receive the class as their first argument, and static methods, marked with @staticmethod, which receive neither an instance nor a class automatically. These are useful in particular situations, but most first class examples need only instance methods.

Instance Attributes and Class Attributes

The attributes assigned through self in __init__ are usually instance attributes. Each object can have a different value. A class attribute is defined directly in the class body and is available through the class and its instances:

class Book:
    category = "Reading"

    def __init__(self, title):
        self.title = title

Here, Book.category is shared as a class-level value unless an instance provides an attribute of its own with that name. This distinction matters for mutable values such as lists: changing a shared class-level list can affect every instance that uses it. If each object needs its own list, create that list inside __init__, for example with self.notes = [].

Common Confusions and Practical Habits

Several small distinctions prevent common bugs:

  • Defining is not creating: a class statement defines a class; calling the class creates an instance.
  • Attributes are not all the same: book.title is an attribute, while book.describe refers to a method bound to that instance.
  • __init__ does not return the object: use it to set up attributes. It should normally return None.
  • Do not confuse assignment and comparison: = assigns a value, while == checks equality.
  • Use instances for per-object state: put data that differs between objects on self, rather than in a shared class attribute.

Classes are not required for every task. A short script that transforms a few values may be simpler with ordinary functions and built-in data structures. A class becomes more helpful when a concept has state that must stay associated with operations—for example, a game character’s position and movement behavior or a task’s description and completion status.

Frequently Asked Questions

What is the difference between a class and an object in Python?
A class defines a type’s structure and behavior; an object is a particular value created from that class. One class can produce many separate objects.

What does self mean in a Python class?
self conventionally names the current instance inside an instance method. Python passes that instance automatically when you call the method through an object.

Is __init__ a constructor?
It is commonly called a constructor by beginners, but its precise role is initialization. Python creates the instance and then calls __init__ to set it up.

What is the difference between a method and a function?
A function is a callable defined independently or stored as a value. A method is a function defined in a class; an instance method receives its instance automatically when called through an object.

When should I use a class instead of a dictionary?
Use a dictionary for simple, flexible collections of named values. Consider a class when those values form a defined kind of thing and need related behavior, validation, or a consistent interface.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.