• python的私有方法


       __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
  • 相关阅读:
    [题解]luogu-P1494 小Z的袜子 普通莫队
    [板子] 线性基
    [板子]字符串-KMP与AC自动机
    [板子]线段树求逆序对
    任务表
    [学习笔记]数列分块入门九题[LOJ6277-6285]
    Python常用高级函数
    Python的闭包和装饰器
    Python的迭代器和生成器
    Python的命名空间
  • 原文地址:https://www.cnblogs.com/topass123/p/16737310.html
Copyright © 2020-2023  润新知