2017-10-08 9 views
0

나는 분수를 생성하기로되어 있고 모든 함수는 "마법의 방법"입니다. 문제는 제 교수가 마법의 방법을 가르쳐주지 못했다는 것입니다. 내가 사용했습니다분수 클래스 파이썬

__init__ 

다른 마법 방법은 사용하지 않았습니다. 나는 이것을 프로그래밍하는 데 2 ​​일이 걸렸으며이 코드를 작성하는 데 필요한 지침이 필요합니다. 내가 여기 프로그램 필요에 가장 가까운 : https://gist.github.com/mustaa/2350807 하지만 그 코드에 무슨 일이 일어나고 있는지 이해할 수 없다

마법 방법은 다음과 같습니다

class Fraction: #I need it in a form like the one on github, but easier to understand 
    __init__ #construct a rational number with a given numerator and denominator 
    __add__ #add two fractions 
    __sub__ #subtract to fractions 
    __eq__ #check if 2 fractions are equal 
    __ne__ #check if 2 are not equal 
    __lt__ #check if one fraction is less than the other 
    __le__ #check if <= 
    __gt__ #check if one fraction is greater than the other 
    __ge__ #check if >= 
    __float__ #gets float representation of fraction called by float() 
    __repr__ #gets a string representation of the Fraction instance, called by str() 

내가 골격 코드를 일단 :

class Fraction, __add__, __eq__ 

남은 과제를 직접 완료 할 수 있습니다.

+3

귀하의 질문에서 과제물을 전달하기 위해 무엇을 제공해야하는지 잘 모르겠습니다. – roganjosh

+1

이것들은 모두 [공식 문서] (https://docs.python.org/3/reference/datamodel.html#special-method-names)에 설명되어 있습니다 – UnholySheep

+0

파이썬의 공식'Fraction' 팩토리 함수는 모두 열려 있습니다. 소스 코드를 포함하고 합리적으로 잘 문서화되어 있습니다. IPython/Jupyter를 사용하는 경우, 'from fractions import Fraction'을 실행 한 다음'Fraction ??'을 실행하십시오 (두 개의 물음표가 소스 코드를 표시합니다). –

답변

1

다음은 쓸데없는 Integer 클래스의 마법 __add____eq__ 방법을 구현하는 방법입니다. 나는 그것을 당신의 Fraction 클래스에 맞추기 위해 당신에게 맡길 것입니다.

class Integer: 

    def __init__(self, value): 
     self._value = value 

    def __add__(self, other): 
     return Integer(self._value + other._value) 

    def __eq__(self, other): 
     return self._value == other._value 
+0

'isinstance (other, Integer) '를 추가하는 것은'__eq__'에서는 좋은 생각 일 수 있지만 간단한 예제에서는 +1하는 것이 좋습니다. – Shadow

+0

@Shadow 예는 가능한 한 산만 함이 없어야합니다. 신호는 일반적으로 마법 방법을 쓰는 방법에 관한 것이므로 다른 유형 (예 : 유형 확인)은 잡음이됩니다. – jacg