1. 程式人生 > 其它 >08.1 property 裝飾器

08.1 property 裝飾器

# -*- coding: utf-8 -*-
# @Time : 2021/8/1 17:47
# @Author : zy7y
# @Gitee : https://gitee.com/zy7y
# @File : property_01.py
# @Project : PythonBooks
from datetime import date, datetime
from dis import dis


class User:

    def __init__(self, name, *, birthday):
        """ * 後面的 引數 birthday 必須已關鍵字引數形式傳遞"""
        self.name = name
        self.birthday = birthday
        self._age = 0 #  程式碼規範,表示不想對外暴露
        self.__demo = None #  私有屬性,Python內部會把其轉換為 類名__demo 形式

    def get_age(self):
        return datetime.now().year - self.birthday.year

    @property
    def age(self):
        """ get
        @property: 計算屬性 呼叫時 只需要 物件.age即可
        :return:
        """
        return datetime.now().year - self.birthday.year

    @age.setter
    def age(self, value):
        """set

        :param value:
        :return:
        """
        self._age = value


if __name__ == '__main__':
    user = User("zy7y", birthday=date(1987,1,1))
    print(user.age)
    # print(user.__demo)  #  訪問私有屬性 AttributeError: 'User' object has no attribute '__demo'
    print(user._User__demo)
    print(dis(User))    #  dis 可列印物件的位元組碼
作者:zy7y 出處:http://www.cnblogs.com/zy7y 本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文連結,否則保留追究法律責任的權利。