HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Classes (Object-Oriented)

Classes (Object-Oriented)

Defining your own data type with class, creating objects with __init__, self and methods.

Simple enough for a 5-year-old to understand

class: define your own type

A class is a "blueprint" for something (e.g., the "Cat" blueprint). You produce individual objects (e.g., Tabby) from this blueprint.

__init__ runs while an object is being created; self represents that object itself.

A Cat class
1
class Cat:
Define the "Cat" blueprint.
DefinitionDefine the "Cat" blueprint.
2
def __init__(self, name):
Runs when the object is born; takes name.
FunctionRuns when the object is born; takes name.
3
self.name = name
Make the incoming name a property of the object.
VariableMake the incoming name a property of the object.
4
tekir = Cat("Tabby")
Produce a cat from the blueprint.
CodeProduce a cat from the blueprint.
5
print(tekir.name)
Writes the object's name: Tekir
Output / InputWrites the object's name: Tekir
DefinitionFunctionVariableCodeOutput / Input
💡 Hint: Don't forget to write self as the first parameter of every method; it's the object itself.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.When does the __init__ method run?

About this topic

A class is a way to group related data and the functions that work on that data into a single structure. Think of a cat: its name and age are data, and its meowing is a behavior. Instead of keeping these as separate variables and separate functions, you combine them in a Cat class.

A class is a blueprint, and an object is a concrete instance produced from that blueprint. You write the Cat class once, and you create hundreds of cat objects from it; each has its own name and age, but they all share the same behaviors. This is called object-oriented programming.

Writing a class is not mandatory in Python; small scripts can be written just fine with functions. Classes are beneficial when data and behavior need to be carried together and when multiple instances are created from the same structure.

What you will learn

  • Defining a class with class and creating an object
  • Assigning initial values with the constructor method
  • What the self parameter means
  • Writing instance methods
  • The difference between class variables and instance variables
  • Defining a readable string representation of an object

When to use?

The clearest indicator that you should use a class is if you constantly pass the same group of variables as parameters to a function. If that group travels together, it means it wants to be an object.

Also, if you are creating many instances from the same structure—users, orders, game characters, each carrying its own state—a class is the natural solution.

Common mistakes

Wrong

class Cat:
    def meow():
        print("meow")

c = Cat()
c.meow()

The first parameter of instance methods must be self; Python automatically passes the object as the first argument. If it's missing, you get the error "TypeError: meow() takes 0 positional arguments but 1 was given".

Correct

class Cat:
    def meow(self):
        print("meow")

c = Cat()
c.meow()

Wrong

class Cat:
    def __init__(self, name):
        name = name

c = Cat("Tabby")
print(c.name)

Because you made an assignment inside the constructor without self, the value only went to a local variable and was not written to the object. The result is "AttributeError: 'Cat' object has no attribute 'name'".

Correct

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

c = Cat("Tabby")
print(c.name)

Wrong

class Cat:
    toys = []

    def add_toy(self, t):
        self.toys.append(t)

A list defined in the class body is shared among ALL objects; when you add a toy to one cat, it appears in all other cats as well. To ensure each object has its own list, it must be created inside the constructor.

Correct

class Cat:
    def __init__(self):
        self.toys = []

    def add_toy(self, t):
        self.toys.append(t)

Frequently asked questions

What exactly is self?

It is the object itself that the method is operating on. When you call a method through an object, Python automatically passes the object as the first argument, and you capture it with the name self. The name is not mandatory, but writing self is a universal convention.

When does the constructor method run?

The moment the object is created, exactly once. It is used to assign initial values and make necessary preparations. Avoid doing heavy work inside it; object creation is expected to be fast.

Are there really private fields in Python?

No. Names starting with a single underscore are a warning meaning "do not use from outside", the language does not prevent this. Double underscores make accidental access harder by mangling the name, but it is still not absolute protection. Python trusts the developer in this regard.

Summary

A class combines data and behavior into a single structure; an object is a concrete instance produced from that template. The three most common mistakes: omitting the self parameter, making assignments in the constructor without self, and defining a shared list in the class body.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code