攝影或3C

Python物件導向(Object-oriented programming,簡稱OOP),類別(Class), 物件(Object), 屬性(Attribute)=變數, 方法(Method)=函式, 建構式(Constructor) def __init__(self,x,y): 計算計程車車資, assert 斷言, 全域變數與區域變數

class Cars:  # 汽車類別

  def __init__(self, color, seats):  # 建構式
      self.color = color  # 顏色屬性
      self.seats = seats  # 座位屬性
      # 注意縮排

  def drive(self):  # 方法
      print(f”My car is {self.color} and has {self.seats} seats”)
benz = Cars(“blue”, 4)  # 物件
class Motors:  # 摩托車類別
  pass
print(“Is Cars?”, isinstance(benz, Cars))
print(“Is Motors?”, isinstance(benz, Motors))

# 存取物件的屬性值:
print(“Color:”, benz.color)  # blue
print(“Seats:”, benz.seats)  # 4
#benz.seats, 存取屬性時,不用()
#像math.pi ,非math.pi()

benz.drive()
#存取方法時,即使沒有參數也要()
執行結果:
class MyClass:  # MyClass() 有無括弧都可以,但: 一定要

  x = 0  # 縮排在class之下
  y = 0

  def myprint(self):  # 縮排在class之下
      self.x += 1  # 再縮排到def之下
      MyClass.y += 1
      print(“(x,y)=({},{})”.format(self.x, self.y))
bracketsNo = MyClass
bracketsYes = MyClass()
brackets_Nobrackets = bracketsNo()

# bracketsNo.myprint() #這行錯誤
# TypeError: myprint() missing 1 required positional argument: ‘self’
bracketsYes.myprint()
bracketsYes.myprint()
bracketsYes.myprint()
brackets_Nobrackets.myprint()
brackets_Nobrackets.myprint()

改寫為OOP, 並使用assert 斷言:
class TaxiCost:
  def __init__(self, km):
      self.km = km

  def fee(self) -> int:
      assert self.km >= 0, \
          f”您輸入的公里數為{self.km},請輸入大於0的數字”
#assert cond, msg相當於
#if not cond : raise AssertionError(msg)
      if 0 <= self.km <= 1.25:
          cost = 70
      elif self.km > 1.25:
          cost = int((70 + 5*(self.km-1.25)/0.2))
      return cost
dist = eval(input(“請輸入公里數: “))
t = TaxiCost(dist)
print(f”您輸入的距離為{t.km} km \n” f”預估車資為:{t.fee()} 元”)

x=50 #全域變數
class Cafe: #無()  <class ‘type’>
  multiple = 2
  x += 2 #現在有兩個x了,一個在class內(52),一個為全域變數(50)
  xx = x+2 #x是50還是52? 從print的結果可知,x=52 (class內)
  print(“xx=”,xx) #52+2=54
  def price(self):
      y     = self.multiple *      x #     x=50
      ySelf = self.multiple * self.x #self.x=52
#一個*x,另一個*self.x,結果會怎樣?
      print(“Price y = %d”     %y )
      print(“Price ySelf = %d” %ySelf )
   
  def shop(self):
      self.price()
      Cafe.multiple = 5
      print(“~~~shop方法結束~~~”)

if __name__ == “__main__”:
      c1 = Cafe()
      c2 = Cafe()    
      c1.shop()  #執行price函數,並將Cafe.multiple改為5
      print(“(c1.multiple,c2.multipe)=({},{})”\
            .format(c1.multiple,c2.multiple))
      c1.multiple = 10 #只針對c1這個物件
      Cafe.multiple = 2 #針對Cafe這個類別
      print(“(c1.multiple,c2.multipe)=({},{})”\
            .format(c1.multiple,c2.multiple))
儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡