I’m fairly new to actual programming languages, and Python is my first one. I know my way around Linux a bit, enough to get a summer job with it (I’m still in high school), and on the job, I have a lot of free time which I’m using to learn Python.
One thing’s been getting me though. What exactly is different in Python when you have expressions such as
x.__add__(y) <==> x+y
x.__getattribute__('foo') <==> x.foo
I know what methods do and stuff, and I get what they do, but my question is: How are those double underscore methods above different from their simpler looking equivalents?
P.S., I don’t mind being lectured on programming history, in fact, I find it very useful to know 🙂 If these are mainly historical aspects of Python, feel free to start rambling.
Well, power for the programmer is good, so there should be a way to customize behaviour. Like operator overloading (
__add__,__div__,__ge__, …), attribute access (__getattribute__,__getattr__(those two are differnt),__delattr__, …) etc. In many cases, like operators, the usual syntax maps 1:1 to the respective method. In other cases, there is a special procedure which at some point involves calling the respective method – for example,__getattr__is only called if the object doesn’t have the requested attribute and__getattribute__is not implemented or raised AttributeError. And some of them are really advanced topics that get you deeeeep into the object system’s guts and are rarely needed. So no need to learn them all, just consult the reference when you need/want to know. Speaking of reference, here it is.