לימוד פייתון : מחלקות 1

Tutorial: Understanding Classes, __init__, and the other.x Concept in Python

This tutorial explains step-by-step how Python classes work, how __init__ creates object attributes, and why calling a method like p1.distance_to(p2) allows us to use other.x.

What is self?

self is a reference to the object that is currently being used.

It means:

  • Inside a class method, self lets the code access the object’s own data.

  • Without self, the object would have no memory, no attributes, and no way to store values.

Key idea

When you write:

p1 = DataPoint(3, 4)

Python internally does:

DataPoint.__init__(p1, 3, 4)

So inside __init__:

  • self = p1

  • x = 3

  • y = 4

Then you assign:

self.x = x # p1.x = 3
self.y = y # p1.y = 4

So self is literally the same object as p1.


Without self the object cannot store anything


When you call a method

If you do:

p1.distance_to(p2)

Python converts it to:

DataPoint.distance_to(p1, p2)

So inside the method:

  • self = p1

  • other = p2

That is why:

self.x

means → p1.x
and

other.x

means → p2.x


Summary (the essence)

self means:

1. Full Code


2. What a Class Is

class DataPoint: defines a new type of object.
Objects created from this class will have the structure and behavior we define inside it.


3. Understanding __init__

The constructor:

This method runs automatically when you create an object:

During this call:

  1. Python creates a new empty DataPoint object.
  2. Python calls:
  3. Inside the constructor:
    • self.x = x creates the attribute p1.x and sets it to 0.
    • self.y = y creates the attribute p1.y and sets it to 0.

After creation:

The same happens for p2.


4. What Happens in p1.distance_to(p2)

The method:

When you call:

Python transforms it internally into:

So inside the method:

  • self refers to p1
  • other refers to p2

This is why other.x works:

  • because other is a DataPoint
  • and every DataPoint has .x and .y created in __init__

Values in our example:

So:


5. Debug Version to See Everything

You can paste this into WordPress to show internal behavior clearly.


6. Connection to AI

This simple class is similar to how AI handles data:

  • A DataPoint is like a sample with features.
  • Distance calculation is used in algorithms like k-Nearest Neighbors, clustering, anomaly detection.

You can expand to more features:

This is the exact idea behind many classical machine-learning models.


If you want, I can prepare a second part of this tutorial:

  • N-dimensional points
  • A mini k-NN classifier
  • A complete beginner AI exercise using only pure Python