Mailing List Archive

Class Methods (as opposed to Instance Methods)
Hi,

I play with Python while a few now (1 month).

My programer background is ObjectPascal, C++ and SmallTalk.

There is an "object-feature" I am not able to reproduce with Python : class
method.
As opposed to instance methods, theese should apply to classes.
ex:

class MyClass:
def myInstanceMethod(self):
print "spam"

def myClassMethod(?, value):
if value=='1' :
return 'MyClass'
elif value=='2' :
return 'Something'
else: return 'What else?'

Instance methods are easy to use:

instance=MyClass()
instance.myInstanceMethod()

But here is how I would like to use class Methods :

print MyClass.myClassMethod(2)

(Note that there is no MyClass().xxx but well MyClass.xxx)

I don't find any way to do that :(
I know it exists class attributes, but it does not fit my needs :(

Please HEEEELP !

---
Olivier Deckmyn, Paris - France
"Any sufficiently advanced technology is indistinguishable from
magic." -Arthur C. Clark
Class Methods (as opposed to Instance Methods) [ In reply to ]
Olivier Deckmyn <olivier.deckmyn@mail.dotcom.fr> wrote:
> I play with Python while a few now (1 month).
>
> My programer background is ObjectPascal, C++ and SmallTalk.
>
> There is an "object-feature" I am not able to reproduce with Python : class
> method. As opposed to instance methods, theese should apply to classes.

python doesn't have class methods. on the other
hand, it makes very little sense to use them, when
you have to put all your code in modules anyway...

</F>
Class Methods (as opposed to Instance Methods) [ In reply to ]
On Fri, Aug 20, 1999 at 01:45:53PM +0200, Olivier Deckmyn wrote:

> Instance methods are easy to use:

> instance=MyClass()
> instance.myInstanceMethod()

> But here is how I would like to use class Methods :
> print MyClass.myClassMethod(2)
> (Note that there is no MyClass().xxx but well MyClass.xxx)
> I don't find any way to do that :(
> I know it exists class attributes, but it does not fit my needs :(

Cant be done(*), class functions expect a class instance as first argument at
all times. You can fake it by giving an unused instance (print
MyClass.myClassMethod(MyClass(),2) or by not using a class at all, but a
module (thus creating a seperate namespace)

file MyClass.py:
def myClassMethod(x):
# etc
^D
file myprogram.py:

import MyClass
print MyClass.myClassMethod(2)

But in general it's best just to avoid using class methods and use either
general methods, module methods (if you aren't writing a module, it's worth
considering to make it a module after all ;-) or just instance methods.
Instance methods dont really have to _use_ the 1st argument (usually 'self')
they're called with.

(*) As far as I know. I've been proven wrong before.

Humbly-y'rs, Thomas.

--
Thomas Wouters <thomas@xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!