OO refactoring trial ??

Chinook chinook.nr at tds.net
Wed Jun 29 00:30:50 EDT 2005


On Tue, 28 Jun 2005 23:23:43 -0400, Kamilche wrote
(in article <1120015423.318185.95600 at g14g2000cwa.googlegroups.com>):

> '''
> You might find this interesting. Note that the object creation in
> main() below could easily be read in from a text file instead,
> thus meeting your requirement of not knowing an item's class
> until runtime.
> 
> Sample output:
> 
> {'password': 'Your Password Here', 'type': 'A', 'logonid': 'Your
> Logonid Here'}
> # did A #
> {'ssn': 555555555, 'type': 'B'}
> # did B #
> {'type': 'BASE', 'address': '501 south street'}
> # did BASE #
> None
> '''
> 
> def Create(type = 'BASE', **kwargs):
>     if type not in _CLASSES:
>         return None # Or return a default object
>     obj = _CLASSES[type](type = type, **kwargs)
>     return obj
> 
> class BASE(object):
>     def __init__(self, **kwargs):
>         self.__dict__.update(kwargs)
>     def __str__(self):
>         return str(self.__dict__)
>     def doit(self):
>         print "# did BASE #"
> 
> class A(BASE):
>     def doit(self):
>         print '# did A #'
> 
> class B(BASE):
>     def doit(self):
>         print '# did B #'
> 
> _CLASSES = {'BASE': BASE, 'A': A, 'B': B}
> 
> def main():
>     obj1 = Create(type = 'A', logonid = 'Your Logonid Here', password 
=
> 'Your Password Here')
>     print obj1
>     obj1.doit()
>     obj2 = Create(type = 'B', ssn = 555555555)
>     print obj2
>     obj2.doit()
>     obj3 = Create(address = '501 south street')
>     print obj3
>     obj3.doit()
>     obj4 = Create(type = 'Missing')
>     print obj4
> 
> main()
> 
> 

Kamilche,

Yes it is interesting and explicit, thank you.  

What I was not clear enough about though, is that at runtime the class object 
creation depends on the information being processed.  That is, the context 
and type of node in the recursed tree.  That's why in my trial the potential 
classes all included a "testit" method and the order of testing is important. 
 Beyond that the "doit" methods all have some varying duplicated expressions, 
 so I was constructing their functionality with code objects.  However, in 
going back over researched material after Paul's comments I noticed another 
technique that might be better in creating functionality and have to study it 
further.

Thanks for the sample,

Lee C





More information about the Python-list mailing list