面向对象编程错误

2024-05-12 06:00:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个从LivingThing类继承的类Animal。 构造函数应该接受4个参数:name、health、food value和可选的参数threshold。你知道吗

如果未指定最后一个参数阈值,则动物对象的阈值 将是一个介于0和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.

Tags: nameself参数getthresholdfoodinitvalue
3条回答

使用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的构造函数。你知道吗

您可以为参数指定默认值,这允许您在调用函数时将其保留在外。在您的例子中,由于您需要动态生成的值(一个随机数),您可以分配一些sentinel值(最常见的是None)并检查它,在这种情况下,生成操作将发生:

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

Python允许参数默认值,因此:

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

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

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

相关问题 更多 >