Simulating Class (was Re: Does Python have Class methods)

Costas Menico costas at meezon.com
Fri May 11 10:45:49 EDT 2001


Ok, so after looking thru how Python works and comments from people, I
came up with what I believe may be the best way to implement Class
methods and Class variables.

Assume that you want your class to be named Foo. Then create a class
called ClassFoo. Inside the class create a class called Foo.

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

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

	class Foo:
		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