zoukankan      html  css  js  c++  java
  • Python基础29类-内置函数(__format__,__slots__,__doc__,__module__,__del__,__call__)

    #__format__
    format_dic={
    'ymd':'{0.year}{0.mon}{0.day}',
    'y-m-d':'{0.year}-{0.mon}-{0.day}',
    'y:m:d':'{0.year}:{0.mon}:{0.day}'
    }
    class Data:
        def __init__(self,year,mon,day):
            self.year=year
            self.mon=mon
            self.day=day
        def __format__(self,format_spec):
            print('我执行了')
            if not format_spec:
                format_spec='ymd'
            fm=format_dic[format_spec]
            return fm.format(self)
    d1=Data(2016,12,26)
    format(d1)
    print(format(d1))
    
    #__slots__
    #可以节省内存,多个实例共用一个字典,但是定义该方法后,类无法增加属性
    class Foo:
        __slots__ = ['name','age']
    f1 = Foo()
    f1.name='alex'
    print(f1.name)
    del f1.name
    
    #__doc__
    class test_doc:
        '我是描述信息'
    pass
    print(test_doc.__doc__)
    
    #__module__
    演示在相对目录libx下的aa文件下建一个C类
    from lib.aa import C
    c1=C()
    print(c1.name)
    print(c1.__module__) #lib.aa
    print(c1.__class__) #calss 'lib.aa.C'
    
    #析构方法__del__
    class test_del:
        def __init__(self,name):
            self.name=name
        def __del__(self):
            print('清内存啦')
    test_del1=test_del('alex')
    del test_del1 #删除一个对象时,会调用__del__方法清理内存,如果不删除对象,则程序运行后python也会自动调用__del__清理内存
    print('-------->')
    
    
    #__call__
    class test_call:
        def __call__(self, *args, **kwargs):
            print('实例执行啦')
    
    test_call1=test_call()
    test_call1()#执行test_call下的__call__方法
    test_call() #执行abc下的__call__方法
  • 相关阅读:
    ASP.NET程序中常用的三十三种代码
    uri
    用XML保存和读取图片
    location
    访问相关节点
    onkeyup,onkeydown,onkeypress
    Asp.net中Server.Transfer,Server.Execute和Response.Redirect的区别
    关于window.showModalDialog()返回值的学习心得
    WP7数据绑定
    hdu 1568
  • 原文地址:https://www.cnblogs.com/josie930813/p/10482096.html
Copyright © 2011-2022 走看看