Python入門題032:類和函式級靜態變數

題目:

實現類和函式級的靜態變數。

影片教程:

Python入門題032:類和函式級靜態變數

程式碼1:

class People: Type = ‘人’ def __init__(self, name): self。name = name def show(self): print(f‘{self。name} 是 {self。Type}’)class Teacher(People): passclass Student(People): passteacher_li = Teacher(‘李老師’)student_ming = Student(‘小明’)student_hong = Student(‘小紅’)print(‘———— 1’)teacher_li。show()student_ming。show()student_hong。show()print(‘———— 2’)People。Type = ‘殭屍’teacher_li。show()student_ming。show()student_hong。show()print(‘———— 3’)People。Type = ‘人’Student。Type = ‘殭屍’teacher_li。show()student_ming。show()student_hong。show()print(‘———— 4’)People。Type = ‘人’teacher_li。show()student_ming。show()student_hong。show()

程式碼2:

def ticktock(): if not hasattr(ticktock, ‘counter’): ticktock。counter = 0 print(f‘歡迎光臨,這是你第 {ticktock。counter} 次來了!’) ticktock。counter += 1ticktock()ticktock()ticktock()