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语言开发的程序执行效率高,开发现率低 ...
随机推荐
- Java 分割、合并byte数组
场景:上传文件较大,把存放文件内容byte数组拆分成小的.下载的时候按照顺序合并. 起初觉得挺麻烦的,写完觉得挺简单. 切割: /** * 拆分byte数组 * * @param bytes * 要拆 ...
- 深入了解MySQL存储索引
(一)关于存储引擎 创建合适的索引是SQL性能调优中最重要的技术之一.在学习创建索引之前,要先了解MySql的架构细节,包括在硬盘上面如何组织的,索引和内存用法和操作方式,以及存储引擎的差异如何影响到 ...
- 算法笔记(c++)--桶排序题目
算法笔记(c++)--桶排序 记得题目是排序,输入n个1-1000的数字然后去重然后排序. 桶排序没毛病 #include<iostream> using namespace std; i ...
- 【转】React-Native 实现增量热更新的思路
所谓热更新就是在不重新安装的前提下进行代码和资源的更新,相信在整个宇宙中还不存在觉得热更新不重要的程序猿. 增量热更新就更牛逼了,只需要把修改过和新增的代码和资源推送给用户下载即可,增量部分的代码和资 ...
- 《构建之法》6-7章读后感、问题及对Scrum的理解
第6章读后感: 看完第六章后了解什么是敏捷流程.“敏捷流程”在软件工程的语境中是一系列价值观和方法论的集合.我觉得敏捷是比较人性化而且让人比较轻松的的一种团队做项目的方法吧,它会比较注重交流,而不是硬 ...
- 20181023-4 Beta阶段第1周/共2周 Scrum立会报告+燃尽图 01
作业要求:[https://edu.cnblogs.com/campus/nenu/2018fall/homework/2383] 版本控制:[https://git.coding.net/lglr2 ...
- 20162328蔡文琛 week06
20162328 2017-2018-1 <程序设计与数据结构>第6周学习总结 教材学习内容总结 队列元素按FIFO的方式处理----最先进入的元素最先离开. 队列是保存重复编码k值得一种 ...
- C++ Primer Plus学习:第七章
C++入门第七章:函数-C++的编程模块 函数的基本知识 要使用C++函数,必须完成如下工作: 提供函数定义 提供函数原型 调用函数 库函数是已经定义和编译好的函数,可使用标准库头文件提供原型. 定义 ...
- erlang node time ticket
Erlang doesn't detect net splits by itself. You could start looking atnet_kernel:set_net_ticktime/2 ...
- (十)Jmeter中的Debug Sampler介绍
一.Debug Sampler介绍: 使用Jmeter开发脚本时,难免需要调试,这时可以使用Jmeter的Debug Sampler,它有三个选项:JMeter properties,JMeter v ...