0

So, as a newbie in Python, I am trying to understand it with the use of some examples. I'd like to understand it better, so I have made this:

class MyClass(object):
     i = 123
     def hot(self):
         self.i = 345
         return self.i

a = MyClass()
print a.hot()

1) Is it correct when I state that hot is a method and therefore needs to be printed like a.hot(), so with the parentheses in the end?

Because, I could do this too:

class MyClass2(object):
     i = 123
     def __init__(self):
         self.i = 345

a = MyClass2()
print a.i

And it both would give me 345.

2) What is the reason I am not using parentheses here? Is it because MyClass2 has not a method with a specific name (hence, it's __init__) so this makes it an entirely different method type?

I would really love some help, because it's quite confusing sometimes. I am trying to understand how __init__ and hot differ, if they are both are seen as methods in Python. Why aren't we using parenthesis for both, then?

3) Also, I guess return is only used when having a method with a real name (like hot), is that correct?

Siyah
  • 2,852
  • 5
  • 37
  • 63
  • `()` *calls* a function. If it's not a function, it doesn't need to be (can't be) called. – deceze Nov 07 '17 at 12:53
  • Most importantly, _read the documentation_! All of this becomes clear after you do so. – cs95 Nov 07 '17 at 12:55
  • Guys, I have checked the documentation and the questions here. The things is: it just confuses me when I don't get a specific answer to my questions. I have closure when experts look to my question and confirm what I ask / say (if correct) or point me in the right direction. I just want a clear answer, instead of having to guess that I am probably right. That's why I am asking it. – Siyah Nov 07 '17 at 12:58
  • 1
    `a.hot` is a function, so you need to call it if you want its `return`ed value. `a.i` is an integer whose value you can access just as is. `__init__` has nothing to do with the second case at all, except that it gets called automatically when `MyClass2` is instantiated. – deceze Nov 07 '17 at 13:05
  • Hi deceze, thank you for your answer. Makes a bit more sense now. I thought hot was a method, because it's a function that is in a class. Am I wrong about that? – Siyah Nov 07 '17 at 13:14
  • 1
    No, that's correct; a function as property of an object is more specifically called a method. – deceze Nov 07 '17 at 13:24
  • I get it now. Thank you very much! – Siyah Nov 07 '17 at 13:26

0 Answers0