OO approach to decision sequence?
Bengt Richter
bokr at oz.net
Sun Jun 26 00:54:42 EDT 2005
On Sat, 18 Jun 2005 03:52:28 -0400, Brian van den Broek <bvande at po-box.mcgill.ca> wrote:
[...]
>
>Now, the same sort of behaviour where the "if type" testing has been
>replaced with code more in keeping with the OOP approach:
>
> >>> class C(object):
>... def report(self):
>... print "Found a C"
>...
> >>> class D(object):
>... def report(self):
>... print "Found a D"
>...
> >>> c = C()
> >>> d = D()
> >>> for item in (c, d):
>... item.report()
>...
>Found a C
>Found a D
> >>>
>
The OP might want to consider factoring report into a base class, e.g.,
>>> class Base(object):
... def art_name(self):
... cname = type(self).__name__
... art = 'an'[:1+(cname.upper() in 'A E F H I L M N O R S X' or
... len(cname)>1 and cname.upper()[0] in 'AEIOU')]
... return art, cname
...
>>> class A(Base): pass
...
>>> class B(Base): pass
...
>>> class F(Base): pass
...
>>> class Foo(Base): pass
...
>>> class U(Base): pass
...
>>> class Uhuh(Base): pass
...
>>> items = A(), B(), F(), Foo(), U(), Uhuh()
>>> for item in items: print 'Found %s %s' % item.art_name()
...
Found an A
Found a B
Found an F
Found a Foo
Found a U
Found an Uhuh
Returning info rather than printing to stdout allows you
to access and use it differently, e.g.,
>>> items[3].art_name()
('a', 'Foo')
>>> items[3].art_name()[1]
'Foo'
(Don't know if the a/an logic is really general ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list