# -*- 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 可打印对象的字节码