Sign in to follow this  

python general classes question

This topic is 3812 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

okay im just learning about classes in the book im reading on python. i was just wondering can someone help explain to me the reasons for having to use def __init__ as the first method in every class? also what is up with self? sorry if u dont understand what self is i mean the first paramater(my book said he uses self always others use other things). why do i have to do def __init__(self, other params, params): or def getName(self):. i just dont get the point of self or init. thanks hey ho hey

Share this post


Link to post
Share on other sites
__init__ is the equivalent of a constructor in python. It's basically a special function called upon an object's creation, where you put your aptly named initialization code for that class. Note that defining an __init__ isn't required unless you're actually going to well, use it.

The "self" issue is kind of a weird syntax thing. If you've worked with a language like C/C++ or Java before, "self" is the equivalent of the "this" pointer/reference. You note that a class's member functions need "self" as the first parameter. This is more or less the same thing with the other languages just mentioned, just that the "this" pointer passing is implicit. "self" is just a way to refer to your object itself.

Share this post


Link to post
Share on other sites
x = SomeClassX() calls SomeClassX.__init__(x) if __init__ exists.

x.some_method() calls SomeClassX.some_method(x) - x is the parameter identified as self.

x.some_other_method(param1, param2) calls SomeClassX.some_other_method(x, param1, param2).

That's it in a nutshell. Now, if you want a discussion of why it's that way...

Share this post


Link to post
Share on other sites

This topic is 3812 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this