2014-04-05 4 views
0

LivingThing 클래스에서 상속 된 Animal 클래스를 만들어야합니다. 생성자는 name, health, food 값 및 선택적 인수 임계 값의 네 가지 매개 변수를 가져야합니다.객체 지향 프로그래밍 오류

마지막 매개 변수 임계 값을 지정하지 않으면 동물 개체 의 임계 값은 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 

내가 올바른 대답을 얻었다 :

이 내 코드입니다.

3 개 및 4 개의 매개 변수를 허용하도록 코드를 수정하려면 어떻게해야합니까? 예를 들어

:

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

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

답변

2

당신은 함수를 호출 할 때 당신이 그것을 유지할 수 매개 변수에 대한 기본값을 지정할 수 있습니다.

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

wow thanks ... 내 코드가 마침내 작동합니다. –

+0

@ user3397867이 대답으로 질문이 해결되면 답변의 왼쪽에있는 체크 표시를 클릭하여 선택해야합니다. 사람들은 대답을 '선택됨'으로 표시하는 사용자에게 대답 할 확률이 더 높습니다. (stackoverflow.com/about) – BorrajaX

0

파이썬은 할 수 있습니다 :이 경우에 생성 동작이 발생하면 동적으로 생성 된 값 (임의의 숫자를) 원하는대로 귀하의 경우에는, 당신은 (가장 일반적으로 None) 일부 센티넬 값을 할당 할 수 있으며 확인 그래서 매개 변수 기본값 :

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

그런 동물 또는 기본 클래스 __init__에, 때 threshold is None를 수행 할 작업을 결정합니다.

동물 및 기본 클래스 모두에서 None 사례를 처리하는 것이 좋습니다. 그런 식으로 서브 클래스 고유의 규칙이 존재하는 경우, 서브 클래스는 그 임계치를 설정할 수 있습니다. 그러나 설정되지 않은 경우 매개 변수를 기본 클래스에 전달하여 기본 규칙이 적용되도록 할 수 있습니다.

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 

트릭이 Animal의 생성자에 전달 threshold=None이다.

+0

감사합니다. 마침내 내 코드 :) –