self.__class__ is a reference to the type of the current instance.

For instances of abstract1, that'd be the abstract1 class itself, which is what you don't want with an abstract class. Abstract classes are only meant to be subclassed, not to create instances directly:

>>> abstract1()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NotImplementedError: Interfaces can't be instantiated

For an instance of a subclass of abstract1, self.__class__ would be a reference to the specific subclass:

>>> class Foo(abstract1): pass
... 
>>> f = Foo()
>>> f.__class__
<class '__main__.Foo'>
>>> f.__class__ is Foo
True

Throwing an exception here is like using an assert statement elsewhere in your code, it protects you from making silly mistakes.

Note that the pythonic way to test for the type of an instance is to use the type() function instead, together with an identity test with the is operator:

class abstract1(object):
    def __init__(self):
        if type(self) is abstract1: 
            raise NotImplementedError("Interfaces can't be instantiated")

type() should be preferred over self.__class__ because the latter can be shadowed by a class attribute.

There is little point in using an equality test here as for custom classes, __eq__ is basically implemented as an identity test anyway.

Python also includes a standard library to define abstract base classes, called abc. It lets you mark methods and properties as abstract and will refuse to create instances of any subclass that has not yet re-defined those names.

Answer from Martijn Pieters on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › self-in-python-class
self in Python class - GeeksforGeeks
January 23, 2026 - In Python, self is a fundamental concept when working with object-oriented programming (OOP). It represents the instance of the class being used. Whenever we create an object from a class, self refers to the current object instance.
Top answer
1 of 6
54

self.__class__ is a reference to the type of the current instance.

For instances of abstract1, that'd be the abstract1 class itself, which is what you don't want with an abstract class. Abstract classes are only meant to be subclassed, not to create instances directly:

>>> abstract1()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NotImplementedError: Interfaces can't be instantiated

For an instance of a subclass of abstract1, self.__class__ would be a reference to the specific subclass:

>>> class Foo(abstract1): pass
... 
>>> f = Foo()
>>> f.__class__
<class '__main__.Foo'>
>>> f.__class__ is Foo
True

Throwing an exception here is like using an assert statement elsewhere in your code, it protects you from making silly mistakes.

Note that the pythonic way to test for the type of an instance is to use the type() function instead, together with an identity test with the is operator:

class abstract1(object):
    def __init__(self):
        if type(self) is abstract1: 
            raise NotImplementedError("Interfaces can't be instantiated")

type() should be preferred over self.__class__ because the latter can be shadowed by a class attribute.

There is little point in using an equality test here as for custom classes, __eq__ is basically implemented as an identity test anyway.

Python also includes a standard library to define abstract base classes, called abc. It lets you mark methods and properties as abstract and will refuse to create instances of any subclass that has not yet re-defined those names.

2 of 6
1

The code that you posted there is a no-op; self.__class__ == c1 is not part of a conditional so the boolean is evaluated but nothing is done with the result.

You could try to make an abstract base class that checks to see if self.__class__ is equal to the abstract class as opposed to a hypothetical child (via an if statement), in order to prevent the instantiation of the abstract base class itself due to developer mistake.

Discussions

python - What is the purpose of the `self` parameter? Why is it needed? - Stack Overflow
A class (instance) method has to ... a reference to the parent class (as self). It's just one less implicit rule that you have to internalize before understanding OOP. Other languages choose syntactic sugar over semantic simplicity, python isn't other languages... More on stackoverflow.com
🌐 stackoverflow.com
Python class __init__ and self
My question what do self an init mean in python class? like this: class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart so why I have to do that? And what do that mean? More on discuss.python.org
🌐 discuss.python.org
0
0
October 4, 2024
Could someone explain the use of "self" when it comes to classes.
Here's an English explanation, basically with functions "def" you can't share variables with other functions. So if you put them a class and put self in front of variable in a function, other functions in that class can call that variable and manipulate it. More on reddit.com
🌐 r/learnpython
116
416
December 8, 2020
Can Someone explain to me what is self and init in python?
watch this . More on reddit.com
🌐 r/learnpython
39
243
October 8, 2022
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
For instance, if you have a function that formats some data from a file object, you can define a class with methods read() and readline() that get the data from a string buffer instead, and pass it as an argument. Instance method objects have attributes, too: m.__self__ is the instance object with the method m(), and m.__func__ is the function object corresponding to the method.
🌐
W3Schools
w3schools.com › python › gloss_python_self.asp
Python Self
Python Examples Python Compiler ... Training ... The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class....
🌐
Python Morsels
pythonmorsels.com › what-is-self
Python's self - Python Morsels
December 28, 2020 - Some programming languages use the word this to represent that instance, but in Python we use the word self. When you define a class in Python, every method that you define must accept that instance as its first argument (called self by convention).
🌐
Python.org
discuss.python.org › python help
Python class __init__ and self - Python Help - Discussions on Python.org
October 4, 2024 - My question what do self an init mean in python class? like this: class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart so why I have to do that? And what do th…
Find elsewhere
🌐
W3Schools
w3schools.com › python › python_class_self.asp
Python self Parameter
Python Examples Python Compiler ... Bootcamp Python Certificate Python Training ... The self parameter is a reference to the current instance of the class....
🌐
Edureka
edureka.co › blog › self-in-python
Self in Python Class | What is the Use of Python Self?
December 5, 2024 - The self in Python is used to represent the instance of the class. With this Self keyword in Python, you can access the attributes and methods of the class.
🌐
Real Python
realpython.com › ref › glossary › self
self (argument) | Python Glossary – Real Python
In Python, self is a widely followed convention for naming the first argument in instance methods within a class.
🌐
MicroPyramid
micropyramid.com › blog › understand-self-and-__init__-method-in-python-class
Understanding Self and __init__ Method in Python Class | MicroPyramid
Understand self and __init__ method in python Class? self represents the instance of the class. By using the self keyword we can access the attributes and methods of the class in python.
🌐
Programiz
programiz.com › article › python-self-why
self in Python, Demystified
This is the reason the first parameter of a function in class must be the object itself. Writing this parameter as self is merely a convention. It is not a keyword and has no special meaning in Python. We could use other names (like this) but it is highly discouraged.
🌐
Reddit
reddit.com › r/learnpython › can someone explain to me what is self and init in python?
r/learnpython on Reddit: Can Someone explain to me what is self and init in python?
October 8, 2022 -

I tried learning OOP from many video tutorials and documentation but I'm not understanding why we really need it or what is the use of it.

So it would be really helpful if someone could explain to me like a child what is the need for self and init in python.

Also, If you could tell me how did you fully grasp the concept of OOP in Python that would be really beneficial to me.

Thank You.

🌐
Sololearn
sololearn.com › en › Discuss › 1121902 › what-is-purpose-of-self-in-python-class
What is purpose of 'self' in python class? | Sololearn: Learn to code for FREE!
self is used to refer an object of a class even before the object is created. if you know c++ or javascript then you may have learned about the 'this' pointer. the same work is of the self keyword in python. for an example, if you want to make ...
🌐
Python.org
discuss.python.org › python help
Understanding classes, init and self - Python Help - Discussions on Python.org
February 16, 2024 - Could you explain this code excerpt? I am learning and trying to get in touch with the logic of classes. class NewWindow(tk.Toplevel): def __init__(self): super().__init__() self.title("Another window")
🌐
Scaler
scaler.com › home › topics › self in python class
Self in Python Class - How to Use Self in Python? | Scaler Topics
February 9, 2024 - The self parameter allows you to access and manipulate the attributes and methods of the object within the class. In Python classes, self serves as a reference to the current instance of the class.
🌐
Educative
educative.io › answers › what-is-self-in-python
What is self in Python?
In Python, the first argument of ... is the convention used by Python developers. It allows each method to access instance variables and other methods belonging to that instance....
🌐
Reddit
reddit.com › r/learnpython › how does “self” in a class work?
r/learnpython on Reddit: How does “self” in a class work?
December 22, 2021 -

You have to add “self” as an argument to a class method. Why this specific syntax and how does it get interpreted? Is this because it inherits from the Python object model?

Is there any language where public methods do not contain “self” as an argument?

Thank you

Top answer
1 of 7
23

Update

In Python 3.11 the module is named typing instead of typing_extensions

from typing import Self


class Node:
    """Binary tree node."""

    def __init__(self, left: Self, right: Self):
        self.left = left
        self.right = right

This might be helpful:

from typing_extensions import Self


class Node:
    """Binary tree node."""

    def __init__(self, left: Self, right: Self):
        self.left = left
        self.right = right

typing_extensions offers a Self class to reference class itself which I think is most elegent way to self-reference(PEP 673).


As others have mentioned, you can also use string literals. But it comes to problem when you have multiple type hints.

# python 3.10
var: str | int

And then you write something like

class Node:
    def __init__(self, var: 'Node' | SomeClass):
        self.var = var

It will raise a TypeError: unsupported operand type(s) for |: 'str' and 'type'.

2 of 7
18

While this, as other answers have pointed out, is not a problem due to the dynamic typing, in fact, for Python3, this is a very real issue when it comes to type annotations. And this will not work (note a type annotation of the method argument):

class A:
    def do_something_with_other_instance_of_a(self, other: A):
        print(type(other).__name__)

instance = A()
other_instance = A()

instance.do_something_with_other_instance_of_a(other_instance)

results in:

   def do_something_with_other_instance_of_a(self, other: A):
   NameError: name 'A' is not defined

more on the nature of a problem here: https://www.python.org/dev/peps/pep-0484/#the-problem-of-forward-declarations

You can use string literals to avoid forward references

Other way is NOT using python3-style type annotation in such cases,

and this is the only way if you have to keep your code compatible with earlier versions of Python.

Instead, for the sake of getting autocompletion in my IDE (PyCharm), you can docstrings like this:

Update: alternatively, instead of using docstrings, you can use "type: " annotations in a comment. This will also ensure that mypy static type checking will work (mypy doesn't seem to care about docstrings):