iT邦幫忙

2021 iThome 鐵人賽

DAY 6
1
自我挑戰組

Python 30天自我挑戰系列 第 6

Day06 - Python基本語法 Part 3,函式與類別

範例程式主要來自於W3Schools

條件式

a = 10
b = 20
if a > b and a >= 0:
  print("a > b")
elif a == b:
  print("a == b")

# 若該條件內暫時沒有要執行的程式碼,需使用「pass」,不可留空
elif a < 0:
  pass
else:
  print("a < b")

迴圈

Python中標準迴圈有while和for兩種,其中break、continue用法跟大部分程式語言差不多,比較特殊的是如果不符合迴圈條件而離開迴圈的話,會執行else區塊(若有提供):

i = 1
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)
else:
  print("Loop end. Now i is " + str(i))

https://ithelp.ithome.com.tw/upload/images/20210918/20141886NAU55QqgXK.png

但若因break跳出,則不會執行else區塊:

i = 1
while i < 6:
  i += 1
  if i == 3:
    continue
  if i == 5:
    break
  print(i)
else:
  print("Loop end. Now i is " + str(i))

https://ithelp.ithome.com.tw/upload/images/20210918/20141886nuiC38jG5y.png

函式

  • 函式的宣告與使用:
def my_function():
  print("This is my function")

my_function()
  • 宣告有引數(argument)的函式;
def my_function(name, age):
  x = "My name is {}. My age is {}."
  print(x.format(name, age))

my_function("Alice", 20)

  • 提供引數預設值:
def my_function(name="None", age=99):
  x = "My name is {}. My age is {}."
  print(x.format(name, age))


my_function("Alice", 20)
my_function()
my_function("Bob")
my_function(name= "Cathy", age=15)
my_function(age=0)

https://ithelp.ithome.com.tw/upload/images/20210918/20141886ikjHn5w4mc.png

  • 如需宣告引數數量可變動,則在引數前面加上「*」,呼叫函式時放入的引數將以Tuple的形式傳入函式內部:
def my_function(*args):
  for x in args:
    print("Input: " + x)

my_function("Apple","Orage","Banana")

https://ithelp.ithome.com.tw/upload/images/20210918/20141886KIqGlNGWWf.png

  • 變數的值域
  1. 在function內部宣告的區域變數,其變數範圍只存在於function內。

  2. 在程式本體宣告的全域變數,變數範圍存在整支程式中。

  3. 當function出現與全域變數相同命名的變數,這時此變數在該function內會視為區域變數,不影響全域變數的數值。

  4. 透過「global」宣告,可在函式內部使用全域變數。

x = 300

# 宣告myfunc1,印出其中區域變數x的數值 = 1000
def myfunc1():
  x = 1000
  print("myfunc1: x = " + str(x))

# 宣告myfunc2,印出全域變數x的數值
def myfunc2():
  global x
  print("myfunc2: x = " + str(x))

myfunc1()
myfunc2()
print("global : x = " + str(x))

https://ithelp.ithome.com.tw/upload/images/20210918/20141886FDIxJX7tBV.png

Class

Python是一種物件導向的程式語言,物件導向的概念已經有很多文章介紹,故以下將直接說明Class和Object相關操作。

  • 建立Class和物件
# 宣告Class
class Book:
  name = "unknown"
  author = "unknown"

# 建立物件
book1 = Book()
print(book1.author)
  • 初始化函式:init(arg1, arg2, arg3) 在建立物件時會被呼叫。
    重要:Class內每個函式的第一個引數arg1將作為該Class的執行個體使用,類似this的用法。
class Book:
  def __init__(self, name, author):
    self.name = name
    self.author = author
  
  def print_name(test):
    print("Book name: " + test.name)


book1 = Book("Pride and Prejudice", "Jane Austen")
book1.print_name()
  • 物件內的屬性可被刪除
class Book:
  def __init__(self, name, author):
    self.name = name
    self.author = author
  
  def print_name(test):
    print("Book name: " + test.name)


book1 = Book("Pride and Prejudice", "Jane Austen")
del book1.name
book1.print_name()

https://ithelp.ithome.com.tw/upload/images/20210918/20141886cCERUZIhMi.png

  • 繼承
    宣告子類別Book,繼承Product
# 宣告父類別
class Product:
  def __init__(self, name, unitprice, quantity):
    self.name = name
    self.unitprice = unitprice
    self.quantity = quantity

  def print_information(self):
    print("Product Name: " + self.name)
    print("Price: " + str(self.unitprice))
    print("Stock: " + str(self.quantity))

# 宣告子類別Book,繼承Product
class Book(Product): 
  pass

prod1 = Product("Apple", 10, 100)
prod2 = Book("Pride and Prejudice", 18, 10)

prod1.print_information()
prod2.print_information()

https://ithelp.ithome.com.tw/upload/images/20210918/20141886o8vKFb1Dee.png

  • 覆寫(Override):
  1. 子類別使用相同的命名會覆蓋父類別。
  2. 使用super().function()繼承父類別的方法(Method)和屬性(Property)
# 宣告父類別
class Product:
  def __init__(self, name, unitprice, quantity):
    self.name = name
    self.unitprice = unitprice
    self.quantity = quantity

  def print_information(self):
    print("Product Name: " + self.name)
    print("Price: " + str(self.unitprice))
    print("Stock: " + str(self.quantity))

# 宣告子類別Book,繼承Product,並覆寫__init__()和print_information()
class Book(Product): 
  def __init__(self, name, unitprice, quantity, author):
    super().__init__(name, unitprice, quantity) 
    self.author = author
  
  def print_information(self):
    super().print_information()
    print("Author: " + self.author)


prod1 = Product("Apple", 10, 100)
prod2 = Book("Pride and Prejudice", 18, 10, "Jane Austen")

prod1.print_information()
prod2.print_information()

https://ithelp.ithome.com.tw/upload/images/20210918/20141886xCCtin6pm0.png


上一篇
Day05 - Python基本語法 Part 2,關於「集合」
下一篇
Day07 - Python基本語法 Part 4,模組、檔案處理與多執行緒
系列文
Python 30天自我挑戰30

尚未有邦友留言

立即登入留言