SV: Python Productivity over C++

David Bolen db3l at fitlinxx.com
Wed Jun 14 21:45:58 EDT 2000


hzhu at knowledgetrack.com (Huaiyu Zhu) writes:

> Now only if somebody could enhance that to check inherited methods too (the
> "more general case").  That is, if a method is not found, go recursively
> into the superclasses.  The following example is not correct at the moment:

Ah, good point - try this variant - I switched to getattr() which
takes the inheritance into account (you could also write your own
recursive function that used Instance.__bases__ to look in the
superclasses).

Note that the object returned by getattr() is a method, whereas the
raw dictionary object is just a function, so there's a small change in
the type comparison.  I'd be interested if anyone more familiar with
the introspective/metaclass features of Python might have a cleaner
way to identify the class member functions:

    def verify_class (Reference, Instance):

	import types

	print "Checking %s for conformity with interface %s" % \
	      (Instance.__name__,Reference.__name__)

	for curmethod in Reference.__dict__.keys():
	    if type(Reference.__dict__[curmethod]) == types.FunctionType:
		try:
		    if type(getattr(Instance,curmethod)) != types.MethodType:
			raise TypeError
		except AttributeError, TypeError:
		    print "Method %s not supported" % curmethod


which for your test cases yields:

>>> verify_class(MyInterface,MyBase)
Checking PostBase for conformity with interface PostInterface
Method method3 not supported
Method method4 not supported
>>> verify_class(MyInterface,MyDerived)
Checking PostDerived for conformity with interface PostInterface
Method method4 not supported

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list