October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Python Classes: Create Objects, Use self, and Reuse Behavior

A practical beginner guide to Python classes: create instances, use self and methods, distinguish shared class attributes from per-instance state, and understand inheritance and dataclasses.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Python class defines a kind of object by grouping data and related behavior. Call the class to create an instance, give that instance its own state, and use methods to work with it. The key beginner distinction is that instance attributes belong to individual objects, while class attributes belong to the class and can be shared.

What is a class in Python?

A class is an object created when Python executes a class statement. You can call the class to create instances—individual objects made from that class. As the Python tutorial puts it, “Classes provide a means of bundling data and functionality together.”

As an Amazon Associate I earn from qualifying purchases.

For example, a Dog class can describe what information each dog stores and what actions a dog can perform:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} says woof"

The class defines the structure and behavior; an instance holds particular data. Create one by calling the class:

dog = Dog("Fido")
print(dog.name)       # Fido
print(dog.speak())   # Fido says woof

Calling Dog("Fido") creates a Dog instance and runs its initializer, __init__, to set up the instance. The initializer is not the operation that creates the instance; it initializes the new object.

What does self mean?

self is the conventional name for the first parameter of an instance method. It refers to the particular instance the method is working with. It is not a Python keyword, but using the familiar name makes class code easier to read.

When you call dog.speak(), Python binds dog to the method’s first parameter. That is why the method can read self.name without you passing dog explicitly. You could write the equivalent call as Dog.speak(dog), though the bound-method form is the normal way to call it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do instance variables and class variables differ?

An instance attribute stores information for one object; a class attribute is defined in the class body and is available through the class and its instances. If an instance is assigned an attribute with the same name as a class attribute, the instance attribute shadows the class attribute for that instance.

Attribute Ownership and access What happens when assigned through an instance
Instance attribute, such as self.name Belongs to one instance; different instances can hold different values. Changes that instance’s attribute.
Class attribute, such as kind below Belongs to the class and can be read through the class or an instance. Assigning the name on an instance creates or updates an instance attribute that shadows the class attribute; it does not change the class attribute.
class Dog:
    kind = "canine"  # class attribute

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

a = Dog("Fido")
b = Dog("Milo")
print(a.name, b.name)  # Fido Milo
print(a.kind, b.kind)  # canine canine

a.kind = "pet"
print(a.kind)           # pet
print(b.kind)           # canine
print(Dog.kind)         # canine

A class attribute can be useful when a value genuinely belongs to the class as a whole. Avoid using a mutable class attribute, such as a list, for data that should be independent for each instance: every instance would access the same list unless it shadows that attribute. Initialize per-instance collections in __init__ instead:

class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []

How does inheritance let classes reuse behavior?

Inheritance lets a derived class reuse attributes and methods from a base class. It can also override a method when the derived type needs different behavior.

class Puppy(Dog):
    def speak(self):
        return f"{self.name} yips"

puppy = Puppy("Pip")
print(puppy.name)      # Pip; inherited initialization
print(puppy.speak())  # Pip yips; overridden method

Here, Puppy inherits Dog’s initializer, so it can initialize name in the same way. Its own speak method replaces the inherited version for puppy instances.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python also supports multiple inheritance, where a class derives from more than one base. The method resolution order (MRO) determines where Python looks for inherited methods and how cooperative super() calls proceed. For a first class, single inheritance is usually simpler to follow.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Does Python have private variables?

Python does not enforce inaccessible private instance variables. A single leading underscore, as in _balance, signals by convention that an attribute is a non-public implementation detail; it does not prevent access.

A double leading underscore, as in __balance, triggers name mangling: Python changes the stored attribute name to reduce accidental clashes with names in subclasses. This is not access control, and it does not make the value truly private.

When should you use a dataclass?

For simple record-like data with named fields, a dataclass can reduce the amount of routine class code you need to write. The official tutorial presents dataclasses as an idiomatic option for this kind of data. A regular class remains a clear choice when custom behavior or other design needs make it a better fit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from dataclasses import dataclass

@dataclass
class Pet:
    name: str
    species: str

pet = Pet("Fido", "dog")
print(pet.name)  # Fido

This dataclass declares two fields and lets you create a Pet by supplying their values. Choose based on the shape of the problem: a concise record of fields suits a dataclass; a regular class is appropriate when it communicates the required behavior or design more clearly.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.