Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Objects __init__

peter keves
peter keves
6,854 Points

Python and Swift vs Java when it comes to instantiation

my first programming language was swift and then i learned myself java and since now I'm learning python I wanted to ask if init() in swift and in python is the same as constructor in java

1 Answer

They are similar, in the sense that, they are the first thing that is run when an object is created.

In Java, you write on constructor with the same name as the class

public class newClass()
{
  public newClass() //This is the no-args constructor
    {
        //stuff goes here
    }
}

If you don't explicitly write out a constructor, the Java compiler creates on for you and runs it whenever the object is created.

in python, we have classes, like Java, but there's an init() function that is called, it works like the constructor in Java:

class new_class():
    def __init__(self):
        # do stuff

If init isn't explicitly written out to do something, Pyhton creates on for you and runs it whenever the object is created.

So, in a sense, yes! As far as I understand it, Java and Python (not sure about swift as I've never learned it) have a similar constructor/init type function.