OO refactoring trial ??
Kamilche
klachemin at comcast.net
Tue Jun 28 23:23:43 EDT 2005
'''
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()
More information about the Python-list
mailing list