Does python have the static function member like C++

goodwolf Robert.Katic at gmail.com
Wed Apr 11 03:40:28 EDT 2007


On Apr 11, 9:09 am, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> 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)

but I think that __new__ is more "low level" and not necessary here,
so I will use:

class AAA (object):
    counter = 0
    def __init__(self):
        self.counter_increase()
    @classmethod
    def counter_increase(cls):
        cls.counter += 1

with yours correction invoking self.counter_increase() instead of more
explicit type(self).counter_increase()




More information about the Python-list mailing list