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



class_demo4.py


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Demo:
   def set_att(self, a=22, b=33):
      self.a = a
      self.b = b
    
   def do_something(self):
      return self.a + self.b
 
d = Demo()
d.set_att()
print(d.do_something())
d.a = 5
print(d.do_something())
  
# 檔名: class_demo4.py
# 作者: Kaiching Chang
# 時間: July, 2014

class_demo5.py


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Demo:
   def set_att(self, a=22, b=33):
      self.__a = a
      self.__b = b
    
   def do_something(self):
      return self.__a + self.__b
 
d = Demo()
d.set_att()
print(d.__a)
print(d.do_something())
d.__a = 5
print(d.__a)
print(d.do_something())
  
# 檔名: class_demo5.py
# 作者: Kaiching Chang
# 時間: July, 2014

exercise1001.py


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class IntegerDemo:
   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
 
i = IntegerDemo()
i.set_value(int(input("v: ")))
i.add(int(input("+: ")))
i.subtract(int(input("-: ")))
i.multiply(int(input("*: ")))
i.divide(int(input("/: ")))
print(i.get_value())
  
# 檔名: exercise1001.py
# 作者: Kaiching Chang
# 時間: July, 2014

exercise1002.py


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class FactorialDemo:
   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
 
i = FactorialDemo()
i.set_value(int(input("n: ")))
print(i.get_value())
  
# 檔名: exercise1002.py
# 作者: Kaiching Chang
# 時間: July, 2014

exercise1003.py


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class FibonacciDemo:
   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
 
i = FibonacciDemo()
i.set_value(int(input("n: ")))
print(i.get_value())
  
# 檔名: exercise1003.py
# 作者: Kaiching Chang
# 時間: July, 2014

the end

沒有留言: