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?
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?
__init__
is a function that initializes the class when it is instantiated. So when you call my_object = Complex()
and create my_object
, __init__
gets called and can be used to precalculate things the class will use later for that specific object, setup attributes the class expects when other methods are called, stuff like that.
self
gives you access to the actual instances of the class, or in the above example my_object
. Every time you call Complex()
, you create a new object, so self
is a reference to the specific object you’ve created. self
is relative to each created object.
I see @facelessuser has already replied to your beginner question so I won’t repeat that.
If you continue studying python, @Big_zhou, you will find many other such constructs. One big grouping is often called something like “dunder” methods. The example you gave is not about something called init
but a wider variable containing a pair of underscores before and after as in __init__
which identifies it as one of many functions you can optionally define in a class, or inherit from a parent class.
Loosely, many operations in python that operate on an object will first look to see if the object has a method defined such as __repr__
and if it exists, use it for some purpose. It allows many kinds of customizations that can make powerful and interesting objects.
The one you asked about tends to be used quite heavily as it is invoked to initialize a new object.
Related:
Hi,
in simplistic terms, you may think of a class
as a template (i.e., a stencil, cookie cutter). They are generally used when the developer intends to create many copies of the same defined object (i.e., a master planned housing community where every nth
house has the same floor plan but with a different address). Just like an nth
house in a master planned community may have a different address (though the same exact design), so to when you create an instance
of a class
where it has its own unique object variable name for referencing but with the same class
definition. Therefore, the self
is a link that creates an association between the class
and the handle name of the object that is created when the class is instantiated.
Internal to a class you see that every defined name is prefixed by the self
keyword. It is done this way because you can’t prefix them with an object name that has yet to be defined. So, the self
is a temporary placeholder until an object has been created.
For example, to fetch the value of a variable named color
inside a class, you would reference it by self.color
. If you want to reference it from outside the class, you would reference it by object_name.color
.
The init method
(method
is what you call a function
when it is defined inside a class
) is a type of dunder
method (so named because they have double underscores) that is automatically run when an instance of a class is created as @facelessuser pointed out. Any other method
has to be qualified
, that is, called by prefixing it by the object name. There are many other dunder
methods for specialized applications, however. The __init__
method is just but one of the many that Python
provides.
In the following example, I have expanded on the class
that you provided. I have assigned (created) two objects (instances of class Complex
). I have added a print statement inside the __inti__
method to show that it is automatically called / run during every class instantiation. Any other regular method has to be qualified (called explicitly by prefixing it by an object name).
class Complex:
def __init__(self, realpart, imagpart, test_frequency):
self.r = realpart
self.i = imagpart
self.f = test_frequency
print('I automatically run at instantiation!')
def print_me(self):
print(f'Impedance: {self.r} + {self.i}i at test frequency {self.f:,} Hz')
impedance_L1 = Complex(34, 25, 450000)
impedance_L2 = Complex(22, 65, 750000)
impedance_L2.print_me()
I hope this helps in better understanding these concepts.
thak u so much
Before we close down this discussion, I want to sum up something.
This began with asking about the this argument in class methods.
Others have provided adequate answers, perhaps more if you followed the resources they pointed to.
What is useful to know is that class methods are function with a difference. They have an implicit first argument supplied under the scenes so that when you call for:
object.method(arg1, arg2)
What actually happens is a bit more like:
object.method(object, arg1, arg2)
Typically, people define the method using a first variable name of this but that is merely a convention. Any reasonable name will do as in this code that has chosen to use me instead of this:
class meClass:
def __init__(me, age):
me.age = age
def nextYear(me):
return me.age + 1
Sam = meClass(5)
Sam.nextYear()
It works fine:
>>> Sam = meClass(5)
>>> Sam.nextYear()
6
I will not go into ways people play games with variants but for functions defined to be part of objects, this applies and has consequences in other ways such as the function having permissions to see or modify aspects of the object as it is considered part of it and not external.
Sorry, I may be missing something here, or this is a typo. It is extremely rare to call the argument representing the instance anything other than self
. It is such a strong convention, that most readers (and some tools) will assume you have made a mistake if you call it anything else.
@Big_zhou You will make this mistake at some stage. Then the first argument will still be the instance, as Avi explains, so your code will compile, but you will get an error later that may be hard to understand. This is easier to spot if the instance is always self
.
In Java, the instance is called this
, but you don’t need to declare it because the compiler takes care of it. So asking why you have to declare it in Python is a reasonable question. I would say it is for language simplicity, so that methods can be the same thing as functions.
By the way, we should call methods like this “instance methods”. A “class method” is where the first argument is the class of the object you applied the method to (conventionally called cls
). That’s a bit harder to explain, and you didn’t mean those. When you’re ready: Built-in Functions — Python 3.13.0 documentation .