【发布时间】:2014-04-16 13:34:54
【问题描述】:
为了以更 Python 和 OOP 风格的方式编写代码,我想知道是否有人可以建议我实现这个概念。
假设我有一个水果基类,比如苹果和香蕉,其中包含该类的基本属性,例如颜色。然后我想要一个继承自果汁的类,它添加了方法和属性,例如量,糖。
粗略的结构可能是:
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
然后我继承我的 Fruit 类的方法:
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 # i.e. some arbitrary function using the class parameters of both this juice class and the original fruit class
所以最终,我可以创建一个像这样的对象:
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
或者,我想知道是否最好不要继承并简单地从 Juice 类中调用水果类。例如
class Juice(object):
def __init__(self, fruit_name, volume, additives):
self.fruit = Fruit(fruit_name=fruit_name)
self.volume = volume # ASIDE: is there an easier way to inherit all parameters from a init call and make them into class variables of the same name and accessible by self.variable_name calls?
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,它是水果的一个属性,虽然可能会与依赖于其他因素的果汁类的糖含量混淆。
或者,最好还是为每个水果有一个单独的类,然后将逻辑语句用于评估通过 Juice 类 init 传递给 Juice 类的 fruit_name 字符串,然后使用例如:
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
# Or some easier way to simply say
self.Fruit = the class which has the same name as the string parameter fruit_name
我很欣赏上述所有方法在理论上可行,尽管我正在寻找开发高效编码风格的建议。在实践中,我想将此应用于不涉及水果的更复杂的项目,尽管该示例包含了我面临的许多问题。
欢迎所有建议/提示/建议阅读链接。谢谢。
【问题讨论】:
-
果汁不是水果,所以这样设置你的类结构是不明智的。
标签: python class oop inheritance