__init__和__new__

#!/user/bin/env python
# -*- coding:utf-8 -*-
# __new__ 在 __init__ 之前执行
# __new__ 是用来控制对象的生成过程, 在对象生成之前
# __init__ 是用来完善对象的
# 如果__new__方法不返回对象, 则不会调用__init__方法


class User:
    def __new__(cls, *args, **kwargs):
        print('in new')
        return super().__new__(cls)

    def __init__(self, name):
        print('in init')
        self.name = name


if __name__ == '__main__':
    user = User('zy')
    print(user.name)

  __getattr__和
__getattribute__
#!/user/bin/env python
# -*- coding:utf-8 -*-
# __getattr__、__getattribute__
# __getattr__ 就是在查找不到属性的时候调用
# __getattribute__ 无条件进入__getattribute__
from datetime import date


class User:
    def __init__(self, name, birthday, info={}):
        self.name = name
        self.birthday = birthday
        self.info = info

    def __getattr__(self, item):
        return self.info[item]

    # def __getattribute__(self, item):
    #     return '__getattribute__'


if __name__ == '__main__':
    user = User('zy', date(year=1998, month=6, day=8), {'company': 'imooc'})
    print(user.company)
    print(user.name)

  

property
from datetime import date, datetime


class User:
    def __init__(self, name, birthday):
        self.name = name
        self.birthday = birthday
        self._age = 0

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

    @property
    def age(self):
        return datetime.now().year - self.birthday.year

    @age.setter
    def age(self, value):
        self._age = value
if __name__ == '__main__':
    user = User('zy', date(year=1998, month=6, day=8))
    user.age = 30      # 调用方法age,@age.setter
    print(user._age)     #获取变量值
    print(user.age)      #调用方法age,@property
    print(user.get_age())  #调用方法get_age

 

posted on 2022-09-28 11:06  topass123  阅读(53)  评论(0编辑  收藏  举报