• python基础---- __getattribute__----__str__,__repr__,__format__----__doc__----__module__和__class__


    目录:

    一、 __getattribute__

    二、__str__,__repr__,__format__

    三、__doc__

    四、__module__和__class__

    一、 __getattribute__                                                               

     1 class Foo:
     2     def __init__(self,x):
     3         self.x=x
     4 
     5     def __getattr__(self, item):
     6         print('执行的是我')
     7         # return self.__dict__[item]
     8 
     9 f1=Foo(10)
    10 print(f1.x)
    11 f1.xxxxxx #不存在的属性访问,触发__getattr__
    12 
    13 回顾__getattr__
    回顾__getattr__
     1 class Foo:
     2     def __init__(self,x):
     3         self.x=x
     4 
     5     def __getattribute__(self, item):
     6         print('不管是否存在,我都会执行')
     7 
     8 f1=Foo(10)
     9 f1.x
    10 f1.xxxxxx
    11 
    12 __getattribute__
    __getattribute__
     1 #_*_coding:utf-8_*_
     2 __author__ = 'Linhaifeng'
     3 
     4 class Foo:
     5     def __init__(self,x):
     6         self.x=x
     7 
     8     def __getattr__(self, item):
     9         print('执行的是我')
    10         # return self.__dict__[item]
    11     def __getattribute__(self, item):
    12         print('不管是否存在,我都会执行')
    13         raise AttributeError('哈哈')
    14 
    15 f1=Foo(10)
    16 f1.x
    17 f1.xxxxxx
    18 
    19 #当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError
    20 
    21 二者同时出现
    二者同时出现

    二、__str__,__repr__,__format__                                           

    改变对象的字符串显示__str__,__repr__

    自定制格式化字符串__format__

     1 #_*_coding:utf-8_*_
     2 __author__ = 'Linhaifeng'
     3 format_dict={
     4     'nat':'{obj.name}-{obj.addr}-{obj.type}',#学校名-学校地址-学校类型
     5     'tna':'{obj.type}:{obj.name}:{obj.addr}',#学校类型:学校名:学校地址
     6     'tan':'{obj.type}/{obj.addr}/{obj.name}',#学校类型/学校地址/学校名
     7 }
     8 class School:
     9     def __init__(self,name,addr,type):
    10         self.name=name
    11         self.addr=addr
    12         self.type=type
    13 
    14     def __repr__(self):
    15         return 'School(%s,%s)' %(self.name,self.addr)
    16     def __str__(self):
    17         return '(%s,%s)' %(self.name,self.addr)
    18 
    19     def __format__(self, format_spec):
    20         # if format_spec
    21         if not format_spec or format_spec not in format_dict:
    22             format_spec='nat'
    23         fmt=format_dict[format_spec]
    24         return fmt.format(obj=self)
    25 
    26 s1=School('oldboy1','北京','私立')
    27 print('from repr: ',repr(s1))
    28 print('from str: ',str(s1))
    29 print(s1)
    30 
    31 '''
    32 str函数或者print函数--->obj.__str__()
    33 repr或者交互式解释器--->obj.__repr__()
    34 如果__str__没有被定义,那么就会使用__repr__来代替输出
    35 注意:这俩方法的返回值必须是字符串,否则抛出异常
    36 '''
    37 print(format(s1,'nat'))
    38 print(format(s1,'tna'))
    39 print(format(s1,'tan'))
    40 print(format(s1,'asfdasdffd'))
    View Code
     1 date_dic={
     2     'ymd':'{0.year}:{0.month}:{0.day}',
     3     'dmy':'{0.day}/{0.month}/{0.year}',
     4     'mdy':'{0.month}-{0.day}-{0.year}',
     5 }
     6 class Date:
     7     def __init__(self,year,month,day):
     8         self.year=year
     9         self.month=month
    10         self.day=day
    11 
    12     def __format__(self, format_spec):
    13         if not format_spec or format_spec not in date_dic:
    14             format_spec='ymd'
    15         fmt=date_dic[format_spec]
    16         return fmt.format(self)
    17 
    18 d1=Date(2016,12,29)
    19 print(format(d1))
    20 print('{:mdy}'.format(d1))
    21 
    22 自定义format练习
    自定义format练习
     1 #_*_coding:utf-8_*_
     2 __author__ = 'Linhaifeng'
     3 
     4 class A:
     5     pass
     6 
     7 class B(A):
     8     pass
     9 
    10 print(issubclass(B,A)) #B是A的子类,返回True
    11 
    12 a1=A()
    13 print(isinstance(a1,A)) #a1是A的实例
    14 
    15 issubclass和isinstance
    issubclass和isinstance

    三、__doc__                                                                              

    class Foo:
        '我是描述信息'
        pass
    
    print(Foo.__doc__)
    它类的信息描述
    class Foo:
        '我是描述信息'
        pass
    
    class Bar(Foo):
        pass
    print(Bar.__doc__) #该属性无法继承给子类
    
    该属性无法被继承
    该属性无法被继承

    四、__module__和__class__                                                     

    __module__ 表示当前操作的对象在那个模块

    __class__     表示当前操作的对象的类是什么

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    class C:
    
        def __init__(self):
            self.name = ‘SB'
    
    lib/aa.py
    lib/aa.py
    from lib.aa import C
    
    obj = C()
    print obj.__module__  # 输出 lib.aa,即:输出模块
    print obj.__class__      # 输出 lib.aa.C,即:输出类
    index.py
  • 相关阅读:
    根据字数自适应项目长度
    Flash与后台数据交互方法总结
    如何让你的网站排名靠前
    C#实现web信息自动抓取
    百度风云榜前50名小偷——专门用于提高你网站的流量!
    ASP资源:ASP编程网上游
    .Net下的HashTable
    强弹代码
    有用的sql语句
    Lotus Domino中使用Xpage技术打造通讯录
  • 原文地址:https://www.cnblogs.com/wangyongsong/p/6769226.html
Copyright © 2020-2023  润新知