On Apr 11, 10:15 am, Bruno Desthuilliers <bruno.
[EMAIL PROTECTED]> wrote:
> goodwolf a écrit :
>
>
>
> > On Apr 11, 9:09 am, Bruno Desthuilliers <bruno.
> > [EMAIL PROTECTED]> wrote:
> >> goodwolf a écrit :
> >> (snip)
>
> >>> 1. In this case you will prefer a classmethod instead a staticmethod.
> >>> 2. If counter is the number of instances of class AAA then you will
> >>> incrase counter inside __init__ method.
> >>> class AAA (object):
> >>>     counter = 0
> >>>     def __init__(self):
> >>>         type(self).counter_increase()
> >> You can call a class method on an instance:
> >>             self.counter_increase()
>
> >> And FWIW, this is probably something I'd put in the constructor (the
> >> __new__ method), not in the initializer.
>
> >>>     @classmethod
> >>>     def counter_increase(cls):
> >>>         cls.counter += 1
> >>> or
> >>> class AAA (object):
> >>>     counter = 0
> >>>     def __init__(self):
> >>>         type(self).counter += 1
> >> Instances have a reference to their class, so you can also write this:
> >>            self.__class__.counter += 1
>
> > OK, you will use something like this:
>
> > class AAA (object):
> >     counter = 0
> >     def __new__(cls):
> >         cls.counter += 1
> >         return super(cls, cls).__new__(cls)
>
>            return super(AAA, cls).__new__(cls)
>
> > but I think that __new__ is more "low level" and not necessary here,
>
> It's of course 'not necessary'. But (IMHO):
> - increasing the class's instance counter is more a responsability of
> the class than a responsability of the instance - and it has nothing to
> do with initializing the instance's state
> - if someone is to subclass AAA, there are fewer chances that he'll
> override the constructer than the initializer, and if he does, there are
> more chances that he won't forget to call on the parent's constructor.
>
> IOW, this is actually *because* it is 'lower level' that I think it's a
> better place for such operations.
>
> But YMMV, of course !-)
>
> My 2 cents...

OK, but then you will use an more flexible constructor:

class AAA (object):
    counter = 0
    def __new__(cls, *args, **kwargs):
        cls.counter += 1
        return super(AAA, cls).__new__(cls, *args, **kwargs)

then you see that you will pay lot resources for a "lower level"
operation.

However if your counter is to consider a low level think, than You are
right, but it's more a personal consideration.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to