Macro like functionality for shorthand variable names
Paul Hankin
paul.hankin at gmail.com
Sat Jun 7 22:15:56 EDT 2008
On Jun 7, 6:13 am, Tilman Kispersky <tilman... at gmail.com> wrote:
> I have python code in a class method translated from C++ that looks
> sort of like this:
>
> >>> self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1])
>
> To make this more readable in C++ I had made macros to achieve this:
> #define du (dydt[1])
> #define u (y[1])
> #define V (y[0])
>
> du = a * (b * V - u);
>
> I realize the value of not having macros in Python. They've tripped
> me up more than once in C++. My question is:
> Is there any way to write a shorterhand more readable version of the
> python code above? I'm doing several calculations one after the other
> and some of the lines are quite long.
First, you can use 's' rather than 'self'.
Then, you can make 'du', 'u' and 'V' properties of your class like
this:
class MyClass(object):
... add this at the end of your class definition ...
def _getu(self): return self.y[1]
def _setu(self, u): self.y[1] = u
u = property(_getu, _setu)
... and similarly for du, V
Using these two tricks, your code line would be:
s.du = s.a * (s.b * s.V - s.u)
--
Paul Hankin
More information about the Python-list
mailing list