Python筆記(*物件導向)


Class 類別名稱:
For example:
class Person:
    def __init__(self,name,age):#建立類別一定要寫這個函式,這是建立實例時初始化的動作,第一個得是self
        self.name = name;
        self.age = age ;
    def sayHello(self):
        print (" Hello, I am %s" % self.name)
    def response(yourName):#此處為靜態函示
        print ("Hello %s." % yourName)
per = Person("Jiehong","20");
print (per.name)
print (per.age)
per.sayHello();
Person.response("Justin");#靜態方法/函式 需要使用class.function,而不需要先指派一個變數為class

一個carclass:
class Car:
    def __init__(self,name,color,speed):
        Car.color = color
        Car.speed = speed
        Car.name  = name
    def printspeed(self):
        print("車子正在以 %s公里的速度前進" % Car.speed )

car = Car("BMW","WHITE","20")
car.printspeed();
print(car.color  +  "   " + car.name  )

繼承:
當子類別繼承了父類別的時候,不會被父類別的型態所限制,而可以增加其他功能
而且,子類別還可以覆蓋父類別的函式。(override)




抽象類別:
1.父類別不實做函式中的程式碼,交由子類別實作
2.抽象類別不能建立實例( instance )
3.如果子類別沒有實作,將會跳出錯誤訊息
4.抽象類別中尚未實作的函示,稱之為抽象函示。
要使用抽象類別,需要使用abc套件
所以要加上一行
from abc import ABCMeta, abstractmethod
這個抽象類別的用意是為了讓父類別先不用實例,只讓子類別使用,但怕子類別在寫的時候忘記使用,所以會跳錯誤,提醒我們要記得使用這個函式。
For example:
from abc import ABCMeta, abstractmethod

class Employee(metaclass = ABCMeta):
    def __init__(self,name,age):
        self.name = name;
        self.age = age;
    @abstractmethod
    def showId():#虛擬函式不須實作,所以用pass
        pass

class Teacher(Employee):#Teacher繼承Employee
    def __init__(self,name, age, tid):
        super().__init__(name, age);#因為是繼承父類別,所以沒有所謂的tid
        self.tid = tid;#只有tid是新的,所以要指派一下
    def showId(self):
        print ("My teacher ID is %s." %self.tid)#要有實例才不會跳bug,注意在寫的時候不能只寫tid,一定要寫self.tid
tea = Teacher('Marry',20,"A1234");#如果沒有實作就會跳bug
tea.showId();




留言

熱門文章