In an attempt to encode more python and OOP-style, I wonder if anyone can advise me to implement this concept.
Let's say I have a base class for fruits, say, an apple and a banana, which contains the basic properties for the class, for example. Colour. Then I want a class that inherits from a fruit called juice, which adds methods and properties, for example. volume, sugar.
The rough structure may be:
class Fruit(object):
def __init__(self, fruit_name):
if fruit_name == 'apple':
self.color = 'green'
self.sugar_content = 2
elif fruit_name == 'banana':
self.color = 'yellow'
self.sugar_content = 3
Then I inherit the methods of my Fruit classes:
class Juice(Fruit):
def __init___(self, fruit_name, volume, additives):
PERHAPS I NEED TO USE A SUPER STATEMENT HERE TO PASS THE fruit_name parameter (which is 'apple' or 'banana' BACK TO THE FRUIT CLASS? I want this class to be able to access sugar_content and color of the the fruit class.
self.volume = volume
self.additives = additives
def calories(self, sugar_added):
return sugar_added + 2*self.sugar_content* self.volume
So, ultimately, I can create an object such as:
my_juice = Juice(fruit_name='apple', volume=200, additives='sugar,salt')
print 'My juice contains %f calories' % self.calories(sugar_added=5)
print 'The color of my juice, based on the fruit color is %s' % self.color
ALTERNATIVELY, I wonder if it is better to inherit and just call the fruit class Juice class. eg.
class Juice(object):
def __init__(self, fruit_name, volume, additives):
self.fruit = Fruit(fruit_name=fruit_name)
self.volume = volume
self.additives = additives
def calories(self, sugar_added):
return sugar_added + 2*self.fruit.sugar_content* self.volume
, self.Fruit.sugar_content , sugar_content . , self.sugar_content, , , .
, fruit_name, Juice Juice init, , :
class Apple(object):
self.color = 'green'
class Banana(object):
self.color = 'yellow'
class Juice(object):
def __init__(self, fruit_name, other params):
if fruit_name == 'apple':
self.Fruit = Apple
self.sugar_content=2
elif fruit_name == 'banana':
self.Fruit = Banana
self.sugar_content=3
self.Fruit = the class which has the same name as the string parameter fruit_name
, , . , , , .
// . .