1

I'm new to python and a total noob with programming so bear with.

If I was building show Person class

    class Person:
      def __init__ (self, Name, Address, Phone, Height, Weight):
        self.name = Name
        self. Address = Address
        self.Phone = Phone
        self.Height = Height
        self.Weight = Weight
        self.PoundserPerInch = int(Height) / int(Weight)

what exactly does the __init__() function do for the code?

1 Answer 1

5

The __init__ method is the constructor. It contains code that is run for each object that is created from that class. It contains code to initialize the object in a proper state.

In your case, you have a Person class which can be used to create Person objects. If you would write:

p = Person('John', '10 Foo Street', '1234567890', 70, 180)

it will create a Person object with those initial values. The constructor takes the values that you passed and it'll assign them to the variables of that object. It will also compute a value called PoundserPerInch.

Sign up to request clarification or add additional context in comments.

1 Comment

Whilst __init__() is commonly called the "constructor", it actually isn't. It's called after the instance has been constructed, which is passed as the self argument. The actual constructor is __new__().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.