I completely pulled the creation logic from the classes:
- parse string
- define an object to create
- create object
So using the following code:
class Fruit(object): def __init__(self, color): self.color = color def observe(self): print "Looks like a tasty %s fruit" % self.color class Apple(Fruit): def __init__(self,color): super(Apple, self).__init__(color) self.tasty = True def bite(self): print "I bite into a tasty apple" fruit = None color,type = "red apple".split() if type == "apple": fruit = Apple(color) if type == "banana" and color == "blue" raise Exception("Welcome to Chernobyl")
edit: In response to your comment on dm03514's answer.
The main difference between this code and your "option 1" is that in this Fruit don’t need to know about your subclasses. In my code, I can do this:
class Banana(Fruit): def __init__(self,color): if color not in ["yellow","green"]: raise Exception("Welcome to Chernobyl") super(Banana).__init__(self,color) if color = "yellow": self.ripe = True elif color = "green:" self.ripe = False def bite(self): print "I bite into a %s banana"%["unripe","ripe"][self.ripe]
Fruit does not need my subclass. In your code, for each new type of fruit, the Fruit class must be updated, which significantly limits any simple way to expand it. If you were developing the library that I wanted, I could not reuse Fruits, since I cannot add banana, orange, or any fruit that you don’t have without changing the code that contradicts code reuse.
user764357
source share