how to use class methods?

Steve Holden sholden at holdenweb.com
Sun Sep 24 15:19:42 EDT 2000


Christopher Paulicka wrote:
> 
> "Mike 'Cat' Perkonigg" <blablu at gmx.net> wrote in message
> news:8FB776878mikecat at 192.168.10.38...
> > Hi!
> >
> > How can I create a class method?
> >
> 
> Well, you can't in the way you are thinking.
> Any method inside the class definition is assumed to be an instance method.
> 
Surely, if a method is defined as part of a class definition then it will
be a method of the class as well as a method of any instances created from
that class definition?

The gotcha is that a call on the method as a class method must give an
explicit instance as a first argumnet, since it will be interpreted as
an unbound method (i.e. one not associated automatically with a
particular instance used to invoke it):

>>> class spam:
	def eggs(self):
		print "spam.eggs called"

>>> spam.eggs()
Traceback (innermost last):
  File "<pyshell#4>", line 1, in ?
    spam.eggs()
TypeError: unbound method must be called with class instance 1st argument
>>> can = spam()
>>> can.eggs()
spam.eggs called
>>> spam.eggs(can)
spam.eggs called
>>> 

> The way I've been doing this is by having one class per file, then having
> "class" methods be methods within the file.
> 
> Christopher
> 
> P.S.  Others provided non-class method solutions to your problem.  Good
> luck.

-- 
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/





More information about the Python-list mailing list