面向对象的编程错误

时间:2014-04-05 17:57:04

标签: python

我需要创建一个继承自Animal类的类LivingThing。 构造函数应该包含4个参数,名称,运行状况,食物值和可选参数阈值。

如果未指定最后一个参数阈值,则为动物对象的阈值 将是0到4之间的随机值。

这是我的代码:

class Animal(LivingThing):
    def __init__(self, name, health, food_value, threshold):
        super().__init__(name, health, threshold)
        self.food_value = food_value

    def get_food_value(self):
        return self.food_value

只有当第四个参数存在时才得到正确答案,即有阈值。

如何修改我的代码,使其允许三个和四个参数?

例如:

deer = Animal("deer", 15, 6)

deer.get_threshold()  ( # Between 0 and 4 inclusive) should give me 2.

3 个答案:

答案 0 :(得分:2)

您可以为参数指定默认值,这样可以在调用函数时将其保留。在您的情况下,由于您需要动态生成的值(随机数),您可以指定一些标记值(最常见的是None)并检查它,在这种情况下您的生成操作会发生:

def __init__(self, name, health, food_value, threshold = None):
    if threshold is None:
        threshold = random.randint(0, 4)
    # ...

答案 1 :(得分:0)

Python允许参数默认值,所以:

def __init__(self, name, health, food_value, threshold=None)

然后在动物或基类__init__中,决定threshold is None时要做什么。

注意在Animal和基类中处理None的情况可能是有意义的;这样,如果存在特定于子类的规则,子类可以设置阈值;但是如果没有设置,参数可以传递给基类,以确保应用默认规则。

答案 2 :(得分:0)

使用kwargs

import random

class LivingThing(object):
    def __init__(self, name, health, threshold):
      self.name=name
      self.health=health
      if threshold is None:
        threshold = random.randint(0, 4)
      self.threshold = threshold

class Animal(LivingThing):
    def __init__(self, name, health, food_value, threshold=None):
        super(Animal, self).__init__(name, health, threshold)
        self.food_value = food_value

    def get_food_value(self):
        return self.food_value


if __name__ == "__main__":
  deer = Animal("deer", 15, 6)
  print "deer's threshold: %s" % deer.threshold

输出:

deer's threshold: 4

诀窍是threshold=None传递给Animal的构造函数。