Counting method calls

Discussion in 'Python' started by =?ISO-8859-1?Q?Ricardo_Ar=E1oz?=, Sep 22, 2007.

  1. Hi, I know I'm being dumb but, why does it not work?

    >>> class MyList(list):

    .... def __init__(self):
    .... self.calls = 0
    .... def __getattr__(self, name):
    .... self.calls += 1
    .... return list.__getattribute__(self, name)

    >>> a = MyList()
    >>> a

    []
    >>> a.append(1)
    >>> a

    [1]
    >>> a.calls

    88
    >>> a.append(3)
    >>> a.calls

    88
    >>> a.sort()
    >>> a

    [1, 3]
    >>> a.calls

    176


    TIA
     
    =?ISO-8859-1?Q?Ricardo_Ar=E1oz?=, Sep 22, 2007
    #1
    1. Advertisements

  2. =?ISO-8859-1?Q?Ricardo_Ar=E1oz?=

    Guest

    On Sep 21, 7:15 pm, Ricardo Aráoz <> wrote:
    > Hi, I know I'm being dumb but, why does it not work?
    >
    > >>> class MyList(list):

    >
    > ... def __init__(self):
    > ... self.calls = 0
    > ... def __getattr__(self, name):
    > ... self.calls += 1
    > ... return list.__getattribute__(self, name)
    >
    > >>> a = MyList()
    > >>> a

    > []
    > >>> a.append(1)
    > >>> a

    > [1]
    > >>> a.calls

    > 88
    > >>> a.append(3)
    > >>> a.calls

    > 88
    > >>> a.sort()
    > >>> a

    > [1, 3]
    > >>> a.calls

    >
    > 176
    >
    > TIA


    __getattr__ only works for attributes that don't exist. The name is
    sorta confusing...
     
    , Sep 22, 2007
    #2
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Honne Gowda A
    Replies:
    2
    Views:
    1,099
    Karl Heinz Buchegger
    Oct 31, 2003
  2. Anon Email

    Counting Objects - Best Method

    Anon Email, Dec 21, 2003, in forum: C++
    Replies:
    6
    Views:
    618
    Anon Email
    Dec 24, 2003
  3. andy6
    Replies:
    2
    Views:
    998
    andy6 via DotNetMonster.com
    Jun 9, 2006
  4. Richard Tobin
    Replies:
    24
    Views:
    1,116
  5. Replies:
    5
    Views:
    365
    red floyd
    Jan 1, 2008
  6. Kyung won Cheon
    Replies:
    0
    Views:
    388
    Kyung won Cheon
    Nov 21, 2008
  7. edwardfredriks

    counting up instead of counting down

    edwardfredriks, Sep 6, 2005, in forum: Javascript
    Replies:
    6
    Views:
    484
    Dr John Stockton
    Sep 7, 2005
  8. Bob
    Replies:
    5
    Views:
    454
Loading...