I am new to Python (coming from MATLAB) and was beginning to learn that classes were a good way to modularize a program. I understand that they are like a “blueprint” that can streamline processes, but I think my understanding of that is faulty. I was reading the documentation and came across this example:
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
x.r, x.i
with an output of
(3.0, -4.5)
And it stumped me. There are no functions known as realpart or imagpart to be passed and yet they are renamed as r and i and instantly work. They don’t appear to be built in functions either. How are realpart and imagpart doing anything?
NOTE: I apologize for the ambiguous title and tags, I’m not really sure what this would be called. I’d appreciate suggestions.
They’re not doing anything: they’re just the names given to the arguments to
__init__. We could call themappleandpearif we liked. When you type__init__is passed three arguments:the instance itself (traditionally called
self), the first explicit argument passed (3.0), and the second explicit argument passed (-4.5). It then stores these as instance variables inself.randself.i.