類最基礎的作用是封裝程式碼:class關鍵字,類名滿足大駝峰
類的組成:屬性,方法(第一個引數是self的函數)
物件通過類建立和初始化
物件的初始化:通過__init__方法初始化
物件的生命週期:
# 物件導向 類
class People:
# __slot__防止使用者惡意新增一些原本不存在的屬性
# __slots__ = ("name", "__age", "skill")
def __init__(self, name, age, skill): # __init__相當於java中的new,self相當於this
self.name = name
self.__age = age # 私有屬性 python中沒有嚴格的私有屬性,不過是障眼法
self.skill = skill
def ability(self):
print("%s love %s" % (self.name, self.skill))
def get_age(self): # 通過get存取私有變數
return self.__age
def set_age(self, new_age):
self.__age = new_age
def run(self):
print("%s run" % (self.name))
maidu = People("maidu", 22, "dance")
print(maidu) # 輸出<__main__.People object at 0x0000000002864C50>
# print(maidu.age) # 輸出22
print(maidu.get_age()) # 輸出22
maidu.set_age(19)
# maidu.sex = "male"
print(dir(maidu)) # 檢視所有的方法和屬性
print(maidu._People__age) # 輸出19
maidu.ability() # 輸出maidu love dance
maidu.run = run
maidu.run(maidu) # 輸出maidu run
案例:# 設計時鐘日曆類,將時鐘類和日曆類進行聯動
# 設計時鐘日曆類,將時鐘類和日曆類進行聯動
class Clock: # 時鐘類
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return "%02d:%02d:%02d" % (self.hour, self.minute, self.second)
def tick(self): # 使秒鐘+1
self.second += 1
if self.second == 60:
self.second = 0
self.minute += 1
if self.minute == 60:
self.minute = 0
self.hour += 1
if self.hour == 24:
self.hour = 0
return "%02d:%02d:%02d" % (self.hour, self.minute, self.second)
clock = Clock(8, 59, 59)
print(clock) # 輸出08:59:59
print(clock.tick()) # 輸出09:00:00
class Calendar: # 日曆類
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __str__(self):
return "%04d-%02d-%02d" % (self.year, self.month, self.day)
def next_day(self): # 使天+1
self.day += 1
if self.day == 31: # 每月暫時按30天處理
self.day = 1
self.month += 1
if self.month == 13:
self.month = 1
self.year += 1
return "%02d-%02d-%02d" % (self.year, self.month, self.day)
c1 = Calendar(2020, 12, 30)
print(c1) # 輸出2020-12-30
print(c1.next_day()) # 輸出2021-01-01
# 時鐘日期聯動
class ClockCalendar(Clock, Calendar):
def __init__(self, year, month, day, hour, minute, second):
Clock.__init__(self, hour, minute, second)
Calendar.__init__(self, year, month, day)
def __str__(self):
return Calendar.__str__(self)+" "+Clock.__str__(self)
def tick(self):
if self.hour == 0:
Clock.tick(self)
elif self.hour == 23:
Clock.tick(self)
if self.hour == 0:
Calendar.next_day(self)
cc = ClockCalendar(2022, 12, 30, 0, 0, 59)
print(cc) # 輸出2022-12-30 00:00:59
cc.tick()
print(cc) # 輸出2022-12-30 00:01:00