[Tutor] On New Style Classes

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Apr 15 16:54:45 EDT 2004


> Well I guess that my post was superflous.

Not at all, it is a valid question, I just wasn't sure what
aspects you were questioning. For what its worth I don't
like the syntax much either.

> seem like they are needed because in the past it just seemed that
you would
> put the function in a module which for all intents looks like a
class.

That works for behaviour that doen't need an instance to work.
But the classic example of class method is a counter that returns
the number of instances.

Thus you can tell things about the class, like whether there are
more than one instance, how many there are, ask how many
superclasses there are, and so on. Its also a useful place
to put factory methods - that is methods which create new
instances. As an example of the latter, say we want the first
instance to be the master and all others to have a reference
to it, we can do that by manually keeping track and passing
it to the constructor, but thats hard to do in a multi-threaded
application. Alternatively we can define a class method that
creates instances. The first one it holds in a variable and
the subsequent it passes the variable to the constructor.
Or maybe we provide a class method to grab a reference to
the first instance (as stored by the factory method)

There are lots of applications for class methods but they
tend to be quite esoteric and are not used a lot, but its
nice to have them available. We already had class level
attributes, so could have the init method update the instance
count for example, but class methods allow a lot more sophistication.

Finally remember that classes are objects too, you can pass
classes around as arguments to functions etc. This really
brings us into the realm of meta programming and thats a
whole new topic, but there are some interesting opportunities
once you pass a class object into a fuinction and allow
the function to call class methods of that object!

But try this for fun:

class C:
   clsAttr = 42
   def instanceMethod(self): print "I'm an instance method"
   def classMethod(c): print "My class attribute is", c.clsAttr
   f = classmethod(classMethod)

class D(C):
   clsAttr = 57

classes = [C,D]
for cls in classes:
    print cls.clsAttr
    cls.f()  # call the class method
    try: cls.instanceMethod()   # no instance!
    except: print 'oops no instance'
    obj = cls()
    obj.instanceMethod()
    obj.f() # works with instances too!
    del(obj)


Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list