我需要创建一个从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.发布于 2014-04-05 17:59:19
您可以为参数指定一个默认值,这允许您在调用函数时将其排除在外。在您的示例中,由于您想要动态生成的值(随机数),您可以分配一些哨位值(最常见的是None)并检查它,在这种情况下发生生成操作:
def __init__(self, name, health, food_value, threshold = None):
if threshold is None:
threshold = random.randint(0, 4)
# ...发布于 2014-04-05 18:00:32
Python允许参数默认值,因此:
def __init__(self, name, health, food_value, threshold=None)然后在动物或基类__init__中,决定当threshold is None时做什么。
注意,在None类和基类中处理大小写可能是有意义的;这样,如果存在特定于子类的规则,子类就可以设置阈值;但如果没有设置,则可以将参数传递给基类,以确保应用默认规则。
发布于 2014-04-05 18:03:12
用夸格
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的构造函数。
https://stackoverflow.com/questions/22884587
复制相似问题