Python classes and objects

organizing code into blueprints and their instances
2025-11-05 07:09
// updated 2025-11-05 10:54

A class in object-oriented programming holds together related information (variables) and actions (functions) as a template or blueprint for objects ... we can think of:

  • a class as an idea of a thing (or person)
  • an object as a representation of an actual, individual thing (or person)

On this page we will look at:

  • writing classes
  • writing objects
    • constructors
    • destructors

Writing classes

In Python, we can write classes with this syntax:

# a blank class
class Person:
  pass

Writing objects

We can then write objects (in the same file anywhere along with the classes) by declaring a variable and calling the class with something called a constructor (essentially, the class name as a function, more on this later on this page):

jon = Person()

Python then reserves memory space for an object with the Person class called jon, i.e. when we use print on jon:

jon = Person()
print(jon)

# Output
# <__main__.Person object at 0xabcdef123456>

...where "0xabcdef123456" would be some random memory address

Constructors

In the last few snippets, we saw the constructor as a function that generates actual instances or objects:

  • by convention the constructor's begins with a capital letter
  • the constructor will contain an __init__ function

About the latter, when we create a new object, we might wish to instantiate it with some already known information:

class Person:
  def __init__(self, name):
    self.name = name

jon = Person("Jon Coder")
print(jon.name)

# Output:
# Jon Coder

Destructors

Python has a special method called a destructor and named __del__ that gets called every time an object gets deleted: it's like a "final hurrah" for the object before it dies!

class Person:
  def __init__(self, name):
    self.name = name

  def __del__(self):
    print(f"Don't cry for me, I, {self.name}, am already dead!")

my_character = Person("Codebear")
del my_character

# Output:
# Don't cry for me, I, Codebear, am already dead!

Seriously, the object (upon deletion) gets "one last chance" to output whatever information it has via the self variable, perhaps to reassure users that they have deleted the correct object!

⬅️ older (in textbook-python)
🐍 Python error handling (try + except + finally)