Does python have the static function member like C++

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Apr 11 04:15:01 EDT 2007


goodwolf a écrit :
> 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)

           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...



More information about the Python-list mailing list