課程
/后端開發
/Python
/python進階
為什么不可以在類里面定義最大公約數函數,如果可以要怎么寫?
2020-05-13
源自:python進階 6-5
正在回答
def __str__(self):
? ? ? ? c, d = self.fun()
? ? ? ? return '%d/%d' % (c, d)
? ? __repr__ = __str__
? ??
? ? def fun(self):
? ? ? ? a, b = self.p, self.q
? ? ? ? if a > b:
? ? ? ? ? ? a, b = b, a
? ? ? ? r = 1
? ? ? ? while r != 0:
? ? ? ? ? ? r = a % b
? ? ? ? ? ? a = b
? ? ? ? ? ? b = r
? ? ? ? c, d = self.p / a, self.q / a
? ? ? ? return c, d
self是必須寫的 所有class中的函數 必須帶上self 除了classmethod等
可以在類中定義,只是在return 時候需要加上class名字(Rational)
舉報
學習函數式、模塊和面向對象編程,掌握Python高級程序設計
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2020-07-09
def __str__(self):
? ? ? ? c, d = self.fun()
? ? ? ? return '%d/%d' % (c, d)
? ? __repr__ = __str__
? ??
? ? def fun(self):
? ? ? ? a, b = self.p, self.q
? ? ? ? if a > b:
? ? ? ? ? ? a, b = b, a
? ? ? ? r = 1
? ? ? ? while r != 0:
? ? ? ? ? ? r = a % b
? ? ? ? ? ? a = b
? ? ? ? ? ? b = r
? ? ? ? c, d = self.p / a, self.q / a
? ? ? ? return c, d
self是必須寫的 所有class中的函數 必須帶上self 除了classmethod等
2020-05-26
可以在類中定義,只是在return 時候需要加上class名字(Rational)