class methods?

Duncan Booth duncan at rcp.co.uk
Wed Jan 12 10:37:14 EST 2000


sjz18 at yahoo.com (Stuart Zakon) wrote in
<20000112145448.29699.qmail at web804.mail.yahoo.com>: 

>However, Python seems to want a class instance to call a method. Does
>every method on a class need self as a parameter?
Yes. Any unbound method in a class needs a class instance as its first 
parameter; any function which you store in a class magically becomes an 
unbound method. You can however store a bound method in a class and call it 
as though it were a class method.
 
>
>Certainly I could make a separate statistics class and instantiate it
>once; however, the nature of the problem is such that it is more natural
>for the statistics collection to be private to the original class. 
>
You could make a separate statistics class which is itself private to the 
original class. For example:

class C:
    class __Private:
        ncalls = 0
        def method(self):
            self.ncalls = self.ncalls + 1
            print "Called %d times" % self.ncalls
    __classmethods = __Private()
    classmethod = __classmethods.method

C.classmethod()
C.classmethod()

'method' isn't restricted to variables in __Private, it can also refer to 
class variables within C as 'C.whatever' so long as C is not changed at the 
module level.

The only other option I can think of is really horrible:
class C:
   def f(): print "This is f"
C.f.im_func()
will call f as a function rather than as a method.



More information about the Python-list mailing list