Python for Fortran programmers 5: Objects?
For a Fortran programmer, reading that “everything in python is an object” does not help. It mostly frightens. Here I’ll try to give some oversimplified definitions so that you can read Python literature without being blocked by the language.
At the beginning you can forget about how objects work, just remember that anything like a Fortran variable (integers, arrays, etc) is an object.
Objects are class instances. Somehow the class is like the definition of the object, whereas the objects are the actual variables. In
REAL :: x,y,z,
REAL would be the class and
x,y,z would be the objects.
Objects have methods and attributes. Again, for simplicity, methods are like Fortran functions, but associated with a certain object. And attributes are variables associated with that object. In Fortran, the closest thing to an attribute would be the fields in a
As attributes and methods are associated with an object, its syntax is special:
In fact, some modules such as numpy (we’ll see more about numpy in the future) have methods implemented also as “normal” module functions. For example, if x is a numpy array we can call its method to get the mean:
or call the module function:
It is not easy to see the utility of objects, because many of the tutorial examples are too trivial. But here is one more example. There are many diagonalization subroutines in lapack. One for real matrices, one for complex, another one for symmetric, etc. They all need different names, and you have to check which one to apply to your particular matrix.
In Python, you could have all these different algorithms as methods in different classes, so that they could have the same name without collisions. Then:
would call the right method depending on what the class of