python基础---- __getattribute__----__str__,__repr__,__format__----__doc__----__module__和__class__
目录:
一、 __getattribute__
二、__str__,__repr__,__format__
三、__doc__
四、__module__和__class__
一、 __getattribute__
class Foo:
def __init__(self,x):
self.x=x def __getattr__(self, item):
print('执行的是我')
# return self.__dict__[item] f1=Foo(10)
print(f1.x)
f1.xxxxxx #不存在的属性访问,触发__getattr__ 回顾__getattr__
回顾__getattr__
class Foo:
def __init__(self,x):
self.x=x def __getattribute__(self, item):
print('不管是否存在,我都会执行') f1=Foo(10)
f1.x
f1.xxxxxx __getattribute__
__getattribute__
#_*_coding:utf-8_*_
__author__ = 'Linhaifeng' class Foo:
def __init__(self,x):
self.x=x def __getattr__(self, item):
print('执行的是我')
# return self.__dict__[item]
def __getattribute__(self, item):
print('不管是否存在,我都会执行')
raise AttributeError('哈哈') f1=Foo(10)
f1.x
f1.xxxxxx #当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError 二者同时出现
二者同时出现
二、__str__,__repr__,__format__
改变对象的字符串显示__str__,__repr__
自定制格式化字符串__format__
#_*_coding:utf-8_*_
__author__ = 'Linhaifeng'
format_dict={
'nat':'{obj.name}-{obj.addr}-{obj.type}',#学校名-学校地址-学校类型
'tna':'{obj.type}:{obj.name}:{obj.addr}',#学校类型:学校名:学校地址
'tan':'{obj.type}/{obj.addr}/{obj.name}',#学校类型/学校地址/学校名
}
class School:
def __init__(self,name,addr,type):
self.name=name
self.addr=addr
self.type=type def __repr__(self):
return 'School(%s,%s)' %(self.name,self.addr)
def __str__(self):
return '(%s,%s)' %(self.name,self.addr) def __format__(self, format_spec):
# if format_spec
if not format_spec or format_spec not in format_dict:
format_spec='nat'
fmt=format_dict[format_spec]
return fmt.format(obj=self) s1=School('oldboy1','北京','私立')
print('from repr: ',repr(s1))
print('from str: ',str(s1))
print(s1) '''
str函数或者print函数--->obj.__str__()
repr或者交互式解释器--->obj.__repr__()
如果__str__没有被定义,那么就会使用__repr__来代替输出
注意:这俩方法的返回值必须是字符串,否则抛出异常
'''
print(format(s1,'nat'))
print(format(s1,'tna'))
print(format(s1,'tan'))
print(format(s1,'asfdasdffd'))
date_dic={
'ymd':'{0.year}:{0.month}:{0.day}',
'dmy':'{0.day}/{0.month}/{0.year}',
'mdy':'{0.month}-{0.day}-{0.year}',
}
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day def __format__(self, format_spec):
if not format_spec or format_spec not in date_dic:
format_spec='ymd'
fmt=date_dic[format_spec]
return fmt.format(self) d1=Date(2016,12,29)
print(format(d1))
print('{:mdy}'.format(d1)) 自定义format练习
自定义format练习
#_*_coding:utf-8_*_
__author__ = 'Linhaifeng' class A:
pass class B(A):
pass print(issubclass(B,A)) #B是A的子类,返回True a1=A()
print(isinstance(a1,A)) #a1是A的实例 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
python基础---- __getattribute__----__str__,__repr__,__format__----__doc__----__module__和__class__的更多相关文章
- __str__,__repr__,__format__
__str__,__repr__ __str__:控制返回值,并且返回值必须是str类型,否则报错 __repr__:控制返回值并且返回值必须是str类型,否则报错 __repr__是__str__的 ...
- 复习python的__call__ __str__ __repr__ __getattr__函数 整理
class Www: def __init__(self,name): self.name=name def __str__(self): return '名称 %s'%self.name #__re ...
- Python——详解__str__, __repr__和__format__
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是Python专题的第10篇文章,我们来聊聊Python当中的类. 打印实例 我们先从类和对象当中最简单的打印输出开始讲起,打印一个实例 ...
- Python基础(2):__doc__、文档字符串docString、help()
OS:Windows 10家庭中文版,Python:3.6.4 Python中的 文档字符串(docString) 出现在 模块.函数.类 的第一行,用于对这些程序进行说明.它在执行的时候被忽略,但会 ...
- python面对对象编程------4:类基本的特殊方法__str__,__repr__,__hash__,__new__,__bool__,6大比较方法
一:string相关:__str__(),__repr__(),__format__() str方法更面向人类阅读,print()使用的就是str repr方法更面对python,目标是希望生成一个放 ...
- Python之路【第六篇】python基础 之面向对象进阶
一 isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 和 issubclass(su ...
- Python基础之面向对象进阶二
一.__getattribute__ 我们一看见getattribute,就想起来前面学的getattr,好了,我们先回顾一下getattr的用法吧! class foo: def __init__( ...
- Python基础-week06 面向对象编程进阶
一.反射 1.定义:指的是通过字符串来操作类或者对象的属性 2.为什么用反射? 减少冗余代码,提升代码质量. 3.如何用反射? class People: country='China' def __ ...
- python基础复习
复习-基础 一.review-base 其他语言吗和python的对比 c vs Python c语言是python的底层实现,解释器就是由python编写的. c语言开发的程序执行效率高,开发现率低 ...
随机推荐
- SQL数据类型(SQL Server六个类型使用)
SQL数据类型是一个属性,它指定任何对象的数据的类型.在SQL中每一列,变量和表达有相关数据类型. 当创建表时,需要使用这些数据类型. 会选择根据表列要求选择一个特定的数据类型. SQL Server ...
- JavaScript学习笔记(一)——JS速览
第一章 JS速览 1 限制时间处理事件 <script> setTomeout(wakeUpUser,5000); function wakeUpUser() { alert(" ...
- HTML5+Bootstrap 学习笔记 3
HTML5 aria-* and role aria是指Accessible Rich Internet Application.role的作用是描述一个非标准的tag的实际作用,而aria-*的作用 ...
- Python:默认参数
Python是个人最喜欢的语言,刚开始接触Python时,总觉得有很多槽点,不太喜欢.后来,不知不觉中,就用的多了.习惯了.喜欢上了.Python的功能真的很强大,自己当初学习这门语言的时候,也记录过 ...
- python struct详解
转载:https://www.cnblogs.com/gala/archive/2011/09/22/2184801.html 有的时候需要用python处理二进制数据,比如,存取文件,socket操 ...
- Java微笔记(8)
Java 中的包装类 Java 为每个基本数据类型都提供了一个包装类,这样就可以像操作对象那样来操作基本数据类型 基本类型和包装类之间的对应关系: 包装类主要提供了两大类方法: 将本类型和其他基本类型 ...
- String、StringBuilder与StringBuffer的区别
1.String类是public.final修饰的. 在Java中,被final修饰的类是不允许被继承的,并且String它的成员方法都默认为final方法. 查看源码得知,String类其实是通过c ...
- win7仿win98电脑主题
http://ys-d.ys168.com/599631823/S7hMfgo3M382J764IOJ8/plus98_for_windows_7_by_ansonsterling.zip
- js & enter
js & enter keycode function (e) { if (e.which === 13 || e.keyCode === 13) { //code to execute he ...
- [C/C++] 指针数组和数组指针
转自:http://www.cnblogs.com/Romi/archive/2012/01/10/2317898.html 这两个名字不同当然所代表的意思也就不同.我刚开始看到这就吓到了,主要是中文 ...