473,734 Members | 2,481 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

what is def __init__?

46 New Member
Hey guys

on my quest to learn python I keep coming across:
def __init__

I think I understand it is defining a method called "init" - but what's with all the underscores. Or is it some builtin method of Python?

Sorry - confused

Cheers!
Jun 19 '07 #1
3 26251
ilikepython
844 Recognized Expert Contributor
Hey guys

on my quest to learn python I keep coming across:
def __init__

I think I understand it is defining a method called "init" - but what's with all the underscores. Or is it some builtin method of Python?

Sorry - confused

Cheers!
__init__ is the function that is called automatically upon an object's construction:
Expand|Select|Wrap|Line Numbers
  1. class Test:
  2.     def __init__(self, num):    # called when object is constructed
  3.         self.value = num
  4.  
  5.     def getVal(self):
  6.         return self.value
  7.  
  8. obj = Test(5)       # Test.__init__ called; sets obj.value to num (5) 
  9.  
  10. print obj.getVal()   # prints "5"
  11.  
The double underscores are used when operator overloading. For example, the above class could be written like this:
Expand|Select|Wrap|Line Numbers
  1. class Test:
  2.     def __init__(self, num):    # called when object is constructed
  3.         self.value = num
  4.  
  5.     def __repr__(self):           # called when object is printed
  6.         return self.value
  7.  
  8. obj = Test(5)       # Test.__init__ called; sets obj.value to num (5) 
  9.  
  10. print obj   # Test.__repr__ called; prints "5"
  11.  
Does that help?


Edit: Just wanted to add that the double underscores in simple terms mean that the function will get called on a special occasion (operator overloading). For example, __init__ gets called when an object is created, __repr__ gets called when the object gets printed, __del__ gets called when object goes out of scope, and there are many others.

Edit 2: Another thing, __init__ is usually used to set up the object by using the arguements to make variables of the object. For example, let's say you have a rectangle class. You'd want the object to have for instance, width and heigth variables. The __init__ would look like this:
Expand|Select|Wrap|Line Numbers
  1. class Rect:
  2.     def __init__(self, width, height):
  3.         self.width = width
  4.         self.height = height
  5.  
  6. myRect = Rect(5, 7)
  7.  
Jun 19 '07 #2
ateale
46 New Member
thanks ilikepython - it makes sense - will read over that a few more times

thanks for explaining!
Jun 19 '07 #3
ilikepython
844 Recognized Expert Contributor
thanks ilikepython - it makes sense - will read over that a few more times

thanks for explaining!
You're welcome, if you have a question, feel free to ask.
Jun 19 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

2
9638
by: Jim Jewett | last post by:
Normally, I expect a subclass to act in a manner consistent with its Base classes. In particular, I don't expect to *lose* any functionality, unless that was the whole point of the subclass. (e.g., a security-restricted version, or an interface implementation that doesn't require a filesystem.) One (common?) exception seems to occur in initialization. I understand stripping out arguments that your subclass explicitly handles or...
7
3560
by: Michele Simionato | last post by:
So far, I have not installed Prothon, nor I have experience with Io, Self or other prototype-based languages. Still, from the discussion on the mailing list, I have got the strong impression that you do not actually need to fork Python in order to implement prototypes. It seems to me that Python metaclasses + descriptors are more than powerful enough to implementing prototypes in pure Python. I wrote a module that implements part of what...
6
3712
by: Steven Bethard | last post by:
So when I'm writing a class and I define an __init__ method, I sometimes haven't called object.__init__, e.g.: class C(object): def __init__(self, x): self.x = x instead of class C(object):
14
6406
by: Axel Straschil | last post by:
Hello! Im working with new (object) classes and normaly call init of ther motherclass with callin super(...), workes fine. No, I've got a case with multiple inherance and want to ask if this is the right and common case to call init: class Mother(object): def __init__(self, param_mother): print 'Mother'
21
12275
by: Sriek | last post by:
hi, i come from a c++ background. i ws happy to find myself on quite familiar grounds with Python. But, what surprised me was the fact that the __init__(), which is said to be the equivlent of the constructor in c++, is not automatically called. I'm sure there must be ample reason for this. I would like to know why this is so? This is my view is more burden on the programmer. Similarly, why do we have to explicitly use the 'self' keyword...
7
5257
by: Kent Johnson | last post by:
Are there any best practice guidelines for when to use super(Class, self).__init__() vs Base.__init__(self) to call a base class __init__()? The super() method only works correctly in multiple inheritance when the base classes are written to expect it, so "Always use super()" seems like bad advice. OTOH sometimes you need super() to get correct behaviour. ISTM "Only use super() when you know you need it" might be
19
1632
by: dickinsm | last post by:
Here's an example of a problem that I've recently come up against for the umpteenth time. It's not difficult to solve, but my previous solutions have never seemed quite right, so I'm writing to ask whether others have encountered this problem, and if so what solutions they've come up with. Suppose you're writing a class "Rational" for rational numbers. The __init__ function of such a class has two quite different roles to play. ...
2
3483
by: Alan Isaac | last post by:
I am probably confused about immutable types. But for now my questions boil down to these two: - what does ``tuple.__init__`` do? - what is the signature of ``tuple.__init__``? These questions are stimulated by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303439 Looking at that, what fails if I leave out the following line? ::
2
1073
by: Neil Cerutti | last post by:
List and deque disagree on what __init__ does. Which one is right? Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) on win32 Type "help", "copyright", "credits" or "license" for more information. deque() test_deque.py even contains a test verifying its __init__
25
2510
by: Erik Lind | last post by:
I'm new to Python, and OOP. I've read most of Mark Lutz's book and more online and can write simple modules, but I still don't get when __init__ needs to be used as opposed to creating a class instance by assignment. For some strange reason the literature seems to take this for granted. I'd appreciate any pointers or links that can help clarify this. Thanks
0
8951
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8783
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9458
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9317
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9248
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8192
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6040
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2184
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.