Python 入門指南 V2.00 - 單元 12 範例及練習程式碼



module_demo.py


import class_demo6

d = Demo(12, 13)
print(d.do_something())
 
# 檔名: module_demo.py 
# 作者: Kaiching Chang 
# 時間: July, 2014

module_demo2.py


import class_demo6

d = class_demo6.Demo(12, 13)
print(d.do_something())
 
# 檔名: module_demo2.py 
# 作者: Kaiching Chang 
# 時間: July, 2014

class_demo6.py


class Demo:
   def __init__(self, v1=11, v2=22):
      self.__a = v1
      self.__b = v2
   
   def do_something(self):
      return self.__a + self.__b

if __name__ == "__main__":
   d = Demo(12, 34)
   print(d.do_something())
 
# 檔名: class_demo6.py 
# 作者: Kaiching Chang 
# 時間: July, 2014

module_demo3.py


from class_demo9 import Demo

d = Demo(12, 13)
print(d.do_something())
 
# 檔名: module_demo3.py 
# 作者: Kaiching Chang 
# 時間: July, 2014

exercise1201.py


class IntegerDemo:
   def __init__(self, v):
      self.__value = v

   def set_value(self, v):
      self.__value = v

   def get_value(self):
      return self.__value

   def add(self, p):
      self.__value += p
   
   def subtract(self, p):
      self.__value -= p

   def multiply(self, p):
      self.__value *= p

   def divide(self, p):
      self.__value /= p

if __name__ == "__main__":
   i = IntegerDemo(int(input("v: ")))
   i.add(int(input("+: ")))
   i.subtract(int(input("-: ")))
   i.multiply(int(input("*: ")))
   i.divide(int(input("/: ")))
   print(i.get_value())
 
# 檔名: exercise1201.py 
# 作者: Kaiching Chang 
# 時間: July, 2014

exercise1202.py


class FactorialDemo:
   def __init__(self, n):
      self.set_value(n)

   def set_value(self, n):
      i = 1
      p = 1
      while i <= n:
         p *= i
         i += 1

      self.__value = p

   def get_value(self):
      return self.__value

if __name__ == "__main__":
   i = FactorialDemo(int(input("n: ")))
   print(i.get_value())
 
# 檔名: exercise1202.py 
# 作者: Kaiching Chang 
# 時間: July, 2014

exercise1203.py


class FibonacciDemo:
   def __init__(self, n):
      self.set_value(n)

   def set_value(self, n):
      n1 = 0
      n2 = 1
      i = 3
      while i <= n:
         n3 = n1 + n2
         n1 = n2
         n2 = n3
         i += 1

      self.__value = n3

   def get_value(self):
      return self.__value

if __name__ == "__main__":
   i = FibonacciDemo(int(input("n: ")))
   print(i.get_value())
 
# 檔名: exercise1203.py 
# 作者: Kaiching Chang 
# 時間: July, 2014

the end

沒有留言: