My fight with classes :)

TheSaint fc14301589 at
Thu Jun 12 09:38:37 CEST 2008

On 04:51, giovedì 12 giugno 2008 Terry Reedy wrote:

First of all a big thank you, all.

> def makeappender():
> data = ['','']
> def appender(val):
> <code that mutates data>
> return appender

I'll give it a try. I just doubting if the data will be shared outside the
Actually, my practice goes to send all variables to the functions and
expecting a returned value. Usually I'm not relying on that module's
variables are read inside a function. Probably I got wrong learning or

> For multiple functions, use classes.

That's what I'm leaning to :)
Then I re-elaborated the class according your points and now it's what I
wanted to be. :)
(last time I forgot to past the first line)
Here it comes:

class StrJoin:
    """ Join a pair of strings according to the leading first letter A or D,
    it returns a list of 2 elements"""

    def __init__(self):
        self.valueA= ''
        self.valueD= ''

    def append(self, value):
        if not isinstance(value, str):
            raise TypeError, 'Wrong type concatenation'
        if value.lower().startswith('a'):
            self.valueA += value
        if value.lower().startswith('d'):
            self.valueD += value
        return [self.valueA ,self.valueD]

    def __getitem__(self,idx):
        if idx > 1 : return self
        if idx == 0 : return self.valueA
        if idx == 1 : return self.valueD

    __call__= append
    def __repr__(self):
        return '['+ self.valueA+ ','+ self.valueD+ ']'

And the shell >>:

>>> from utilities import StrJoin as zx
>>> k =  zx()
>>> k
>>> k('add')
['add', '']
>>> k[2]
>>> k[1]
>>> k[0]
>>> k('dad')
['add', 'dad']
>>> k('sad')
['add', 'dad']
>>> k('Alfa')
['addAlfa', 'dad']
>>> k('Dude')
['addAlfa', 'dadDude']
>>> k('Omega')
['addAlfa', 'dadDude']
>>> k('Dome')
['addAlfa', 'dadDudeDome']
>>> k.append[k]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'instancemethod' object is unsubscriptable
>>> k(89)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "", line 33, in append
    raise TypeError, 'Wrong type concatenation'
TypeError: Wrong type concatenation

Mostly I'll use the call option. I also like to pass it into a function in
order to modularize the loop where it gets started.

Mailsweeper Home :

More information about the Python-list mailing list