"static" class functions?

Costas Menico costas at meezon.com
Tue May 22 23:49:28 EDT 2001


"Neil" <mac4-devnull at theory.org> wrote:

>I am interested in having a function associated with a class that can be
>run without an instance of the class.
>
>For example:
>
>class Foo:
>    __val = 5
>    def printPrivate():
>        print Foo.__val
>

I wrote this in an older thread. You use a nested class to achieve
"static" or more accurately class methods and class variables:

Here is the class definition example type in a file call fooclass.py

class ClassFoo:
	# class var
	nm = 1
	
	#class method
	def getNm(self):
		return self.nm

	class Foo:
		# instance methods
		def __init__(self):
			pass
		
		def incr(self):
			ClassFoo.nm+=1


And here is an example of how you can use it. (I typed it
interactively)

#>>> from fooclass import *
#>>> Foo=ClassFoo()
#>>> obj1=Foo.Foo()
#>>> obj2=Foo.Foo()
#>>> obj1.incr()
#>>> Foo.nm
2
#>>> obj2.incr()
#>>> Foo.nm
3
#>>> Foo.getNm()
3
#>>> 

Notice that obj1.nm or obj2.nm will not work since these are instances
of Foo. Also class Foo has no access to the instance methods. As it
should be.

In Smalltalk classes are really just objects of their metaclass. In a
way this is what is being accomplished here by "Foo=ClassFoo()"
although not automatically. What would be intresting to follow-up is
make ClassFoo a subclass of a class Class. This can then allow all
classes to inherit standard methods from Class.

Costas



More information about the Python-list mailing list