python3自學之路-筆記24—生命週期方法

老規矩,先上代碼:

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# File  : 生命週期方法.py
# Author: DaShenHan&道長-----先苦後甜,任憑晚風拂柳顏------
# Date  : 2019/11/10

class Person:
    __personCount = 0  #定義一個類方法,並且私有化,確保安全性。用於計數實例化了多少個對象
    def __init__(self): #實力初始化時調用這裏的方法
        print("計數 +1")
        Person.__personCount +=1

    def __del__(self):#實力被釋放時調用這裏的方法
        print("計數 -1")
        self.__class__.__personCount -=1

    @staticmethod  #定義一個靜態方法
    def  log():
        print(f"當前的人數是{Person.__personCount}")

    @classmethod #定義一個類方法
    def  log1(cls):
        print(f"當前的人數是{cls.__personCount}")

Person.personCount = 100 #嘗試外部改變類方法(安全性測試)
p = Person()
p2 =  Person()
Person.log()
del p
Person.log()
Person.log1()

運行結果如圖:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章