๐Ÿ—๏ธClasses: __init__, self, Instance MethodsLESSON

Python Classes: Defining Your Own Types

A class is a blueprint for creating objects. Objects bundle together related data (attributes) and behavior (methods). Python's class system is clean, flexible, and central to how many major libraries are designed.

Defining a Class

Class names use PascalCase by convention. Each call to the class creates a new, independent instance.

init: The Initializer

__init__ is called automatically when you create an instance. It sets up the initial state of the object. Note: __init__ doesn't create the object โ€” Python creates it first, then calls __init__ to initialize it.

self: The Instance Reference

self is a reference to the current instance of the class. When you call rex.bark(), Python automatically passes rex as the first argument to the method (which receives it as self). The name self is a convention, not a keyword โ€” you could use any name, but always use self.

Instance Methods

Instance methods are functions defined inside a class. They always receive self as their first parameter. They can read and modify the instance's attributes.

Instance Variables vs Class Variables

Instance variables belong to each object independently. Class variables are shared across all instances.

Use class variables for data that should be the same across all instances: constants, configuration, counters.

str: Human-Readable Representation

__str__ is called by print() and str(). Without it, you get something like <__main__.Dog object at 0x10a3b2e80>.

If you only define one, define __repr__. It's used as a fallback for str() too, and it's shown in the REPL.

Object Creation: What Actually Happens

When you call Dog("Rex", "German Shepherd", 3):

  1. Python calls Dog.__new__(Dog) โ€” creates the object in memory
  2. Python calls Dog.__init__(instance, "Rex", "German Shepherd", 3) โ€” initializes it
  3. The initialized instance is returned to the caller

You rarely override __new__, but it's good to know the full picture.

type() and isinstance()

type(obj) returns the exact class of an object. isinstance(obj, Class) checks if an object is an instance of a class or any of its subclasses.

Prefer isinstance() over type() == because it handles inheritance correctly.

Default Argument Values in init

A Complete Example

Knowledge Check

What is the purpose of `self` in a Python class method?

What is the difference between a class variable and an instance variable?

Why is `isinstance(obj, MyClass)` preferred over `type(obj) == MyClass`?