Class static methods

Guillaume forums at memoire.com
Mon Jul 24 06:47:15 EDT 2000


Well, now that I have class static vars, I need class static methods...
Is it possible in Python ? Not sure...

class A:
	def g():
		print "hello"

A.g() fails on TypeError: unbound method must be called with class
instance 1st argument

So maybe I need to use __call__. Here is a solution but it is not very
elegant... Maybe you know some better one ? Is there at least some way
to factorize Redirect to handle any number of args ?

I would like A.m(), a.m(), B.m() and b.m() to be equivalent (= same
call) where A is a class, a=A(), B is a class inheriting from A, b=B().

Regards, Guillaume

#### CODE ####

class Redirect0:
	nm=None
	def __init__(self,name):
		print name
		self.nm=name
	def __call__(self):
		exec self.nm+"()"

class Redirect1:
	nm=None
	def __init__(self,name):
		print name
		self.nm=name
	def __call__(self,p1):
		exec self.nm+"(p1)"

class A:
	pass

def A_g():
	print "static method of A without args"

def A_h(x):
	print "static method of A with 1 arg: x=%s" % x

A.g=Redirect0("A_g")
a=A()
a.g()
A.g()

A.h=Redirect1("A_h")
a=A()
a.h(1)
A.h(1)

class B(A):
	pass

# redefine g in B
def B_g():
	print "static method of B without args"
B.g=Redirect0("B_g")
b=B()
b.g()
B.g()
b.h(2)
B.h(2)


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list