0

I need to create a class Animal, inherited from the LivingThing class. The constructor should take in 4 parameters, name, health, , food value, and an optional argument threshold.

If the last parameter threshold is not specified, the threshold of the animal object will be a random value between 0 and 4 inclusive.

This is my code:

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

I got the correct answer only when the fourth parameter exist i.e. there's threshold.

How do I modify my code such that it allows three and four parameters?

For example:

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

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

3 Answers 3

2

You can specify a default value for parameters, which allows you to keep it out when calling the function. In your case, as you want a dynamically generated value (a random number), you can assign some sentinel value (most commonly None) and check for it, in which case your generation operation happens:

def __init__(self, name, health, food_value, threshold = None):
    if threshold is None:
        threshold = random.randint(0, 4)
    # ...
Sign up to request clarification or add additional context in comments.

1 Comment

@user3397867, If this answer solves your question, you should click on the tick on the left side of the answer to select it as chosen. People are more likely to answer users who mark answers as 'selected' (stackoverflow.com/about )
0

Python allows parameter defaults, so:

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

Then in Animal or base class __init__, decide what to do when threshold is None.

Note it may make sense to handle the None case in both Animal and base class; that way the subclass can set the threshold if there is a subclass-specific rule for this; but if not set, the parameter could be passed along to the base class to ensure a default rule is applied.

Comments

0

With 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

That outputs:

deer's threshold: 4

The trick is the threshold=None passed to the Animal's constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.