newbie: self.member syntax seems /really/ annoying

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Sep 12 08:38:13 EDT 2007


On Wed, 12 Sep 2007 03:21:58 -0700, Charles Fox wrote:

> I've just started playing around with Python, as a possible replacement
> for a mix of C++, Matlab and Lisp.  The language looks lovely and clean
> with one huge exception:  I do a lot of numerical modeling, so I deal
> with objects (like neurons) described mathematically in papers, by
> equations like
>     a_dot = -k(a-u)
> In other languages, this translates nicely into code, but as far as I
> can tell, Python needs the ugly:
>     self.a_dot = -self.k(self.a-self.u)

I think you've been seriously mislead. You don't NEED self. That's only 
for writing classes.

Although Python is completely object oriented, and everything is an 
object, you don't have to put your code in classes.

Instead of doing something like this:

class Adder(object):
    """Pointless class to add things."""
    def __init__(self, value):
        self.value = other
    def add(self, other):
        x = self.value + other
        return float(x)

you don't need a class. Just write a function:

def add(x, other):
    """Function that adds other to x."""
    return float(x + other)

Here's how I would write your function above:

def function(a, u, k):
    """Calculate a_dot from a, u and k."""
    return -k(a-u)

And here is how I would use it:

a = 57 # or whatever...
u = 54
k = 3
a_dot = function(a, u, k)


See? Not a single "self" in sight.


You might also like to read about a strange, bizarre programming that 
forces you to put everything inside classes:

http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html




-- 
Steven.



More information about the Python-list mailing list