View Single Post
Old Dec 4th, 2007, 6:27 PM   #2
ZenMasterJG
Hobbyist Programmer
 
ZenMasterJG's Avatar
 
Join Date: Nov 2004
Location: Boston, MA
Posts: 148
Rep Power: 4 ZenMasterJG is on a distinguished road
Send a message via AIM to ZenMasterJG
Re: Object-Oriented Habits

Personally, I think it depends on the program. If the two inheriting classes would be implemented substantially differently, then definitely go with inheritance. If the differences are fairly small, then I'd go with your second solution, though I'd probably wrap the constants into the class as class attributes, like so:
python Syntax (Toggle Plain Text)
  1. class Child(object):
  2. MALE=1
  3. FEMALE=2
  4. def __init__(self, gender):
  5. self.gender=gender
  6.  
  7. def doSomething(self):
  8. if self.gender==Child.MALE:
  9. print 'male'
  10. elif self.gender==Child.FEMALE:
  11. print 'female'
  12. else:
  13. print 'error'
  14.  
  15. boy=Child(Child.MALE)
  16. boy.doSomething()
I think that way achieves better encapsulation, and if nothing else it avoids cluttering up your namespaces a bit.

(And, as an aside, you should probably start getting in the habit of using new style classes (i.e inheriting everything from object, if it isn't inheriting anything else) instead of old-style as you're using now.
ZenMasterJG is offline   Reply With Quote