[Tutor] Python Assignment Expression and Callable Expression

Cameron Simpson cs at zip.com.au
Fri Sep 19 07:04:11 CEST 2014


On 19Sep2014 02:41, Wang Lei (ERIAN) <l.wang at ntu.edu.sg> wrote:
>I really believe that python is a great language but assignment and callable are not flexible:

Some flexibilities are too much. But there are ways to do what you ask...

>I wish that I can do this:
>
>  class matrixArray(list):
>  bla bla bla
>    def __call__(self, rid, cid):
>        return self.head[rid][cid]
>
>Once I call mat(1,1), I can get a result. but I want it more a value not a reference.

You're going to need to be less vague. If the result is, for example, an int, 
in what fashion is it a value instead of an int as far as you are concerned?  
Please describe this issue more fully.

>Considering "mat(1,1) = 5" expression, I wish the parser can dynamically map "mat(1,1)" to reference of value of that "or anonymous reference" or reference defined in class. I don't want to modify the lexical parsing in C++ but failed after trying different method in pythonic ways:

Define the __setitem__ method on your matrixArray class. Then you can write:

   mat[1,1] = 5

which is arguably more natural anyway. Assignment and calling are two very 
different things, and in python they are written differently. That is a good 
thing.

>decorator: fun -> object mapping, because it just substitute function name with new function and cannot read "self" object.

I must be missing your point here, too. It does just substitute a new function, 
but that new function can (and generally must) access "self" to do its work.

I think you are forgetting that the @decorator action occurs at the time the 
class is defined, not at the time the function is called.

Cheers,
Cameron Simpson <cs at zip.com.au>

More computing sins have been committed in the name of performance,
without necessariliy achieving it, than for all other reasons
combined.       - Wulf


More information about the Tutor mailing list