Python 語法


Python 語法

Hello World

print("Hello World")

註解

# 註解

宣告

Python 有自動型別判斷 無須指定型別
i = 1
d = 1.0
s = "string"
b = True // False
arr = [1, 2, 3]

運算子

x = 2
y = 3
z = x + y
z = x - y
z = x * y
z = x / y
z = x // y # 只取整數解
z = x % y # 取餘數
z = x ** y # x的y次方

IF ELSE

grade = 90
if grade >= 90:
    print('Excellent!')
elif grade >= 60:
    print('Good enough!')
else:
    print('Loser!')

For loop

arr = ["A", "B", "C", "D"]

# 印出value
for v in arr:
  print(v)

# range 
for i in range(0, len(arr)):
  print(i)

# 印出 index, value
for i,v in enumerate(arr):
  print(i, "->", v)

While loop

i = 0 
while i < 10:
  print(i)
  if i == 3:
    continue
  if i >= 6:
    break
else:
  # while 第一次條件為 False 才會執行
  print("i >= 10")

Function

def f():
  print("hello python function")
def f(name):
  print("hello ", name)
def f(name):
  return "hello " + name
count = 0 
def f():
  global count // 宣告使用全域變數 count
  count += 1

Class

class Cat:
  name = "name"
  def sound():
    print("喵")

cat = Cat()
cat.name = "秀秀"
print(cat.name)
cat.sound()

建構子

class Cat:
  def __init__(self, name):
    # 建構子 建立物件時會呼叫
    self.name = name
  
  def sound(self):
    print("喵")

cat = Cat("秀秀")
print(cat.name)
cat.sound()
如果有變數不想被外部使用可以使用兩個底線作為宣告
class Cat:
  def __init__(self, name):
    self.__name = name # 如果有變數不想被外部使用可以使用兩個底線作為宣告

cat = Cat("秀秀")
print(cat.name) # AttributeError: 'Cat' object has no attribute '__name'

繼承 Extends

class Animal():
  def sound(self):
    print("不知名的叫聲")

class Cat(Animal):
  def __init__(self, name):
    self.name = name
  def sound(self):
    print("喵")

cat = Cat("秀秀")
print(cat.name)
cat.sound()
python 也可以多重繼承
class Animal():
  def sound(self):
    print("不知名的叫聲")

class Cute():
  def playingCute(self):
    print("裝可愛")

class Cat(Animal, Cute):
  def __init__(self, name):
    self.name = name
  def sound(self):
    print("喵")

cat = Cat("秀秀")
print(cat.name)
cat.sound()
cat.playingCute()

抽象類別 Abstract class

Animal 未實作 voice 因此 Cat 在繼承後 必須實作
class Animal():
  def sound(self):
    print(self.voice) # voice 未實作

class Cat(Animal):
  def __init__(self, name):
    self.name = name
    self.voice = "喵" # 實作 voice

cat = Cat("秀秀")
print(cat.name)
cat.sound()
上例說明 簡單的 abstract 但聰明的你應該也覺得怪怪的吧
那是因為 python 沒有 abstract class 或是 interface
是依照設計者的自我約束但 但是大家都知道的 呵呵
因此有 abc 庫來強制約束設計者
import abc
class Animal(abc.ABC):
  @abc.abstractmethod
  def sound(self):
      return NotImplemented

class Cat(Animal):
  def __init__(self, name):
    self.name = name
  def sound(self):
    print("喵")

cat = Cat("秀秀")
print(cat.name)
cat.sound()

WRITTEN BY
Aki

熱愛寫code的開發者,專注於 Android 手機 Native App 開發,對於 IOS 也有涉略。閒暇之餘也學習 JavaScript 等前端框架