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语言开发的程序执行效率高,开发现率低 ...
随机推荐
- 【jpeg_Class 类】使用说明
jpeg_Class类是针对图片操作类,可以获取图片属性.等比例缩略图片.裁切图片.图片上打印文字及打印水印等功能. 目录 原型 参数 返回 说明 Sub load(byVal path) path ...
- 学习使用Git 版本控制 代码管理
title: 学习使用Git 版本控制 代码管理 notebook: 经验累积 tags:Git --- Git 版本控制 学习教程 Git版本控制器,可以作为程序员.计算机科学和软件工程的研究人员在 ...
- 梯度下降算法以及其Python实现
一.梯度下降算法理论知识 我们给出一组房子面积,卧室数目以及对应房价数据,如何从数据中找到房价y与面积x1和卧室数目x2的关系? 为了实现监督学习,我们选择采用自变量x1.x2的线性函数来评估因变 ...
- Thunder团队第七周 - Scrum会议2
Scrum会议2 小组名称:Thunder 项目名称:i阅app Scrum Master:王航 工作照片: 参会成员: 王航(Master):http://www.cnblogs.com/wangh ...
- Alpha 冲刺(10/10)
队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 测试整体软件 展示GitHub当 ...
- VK Cup 2015 - Round 2 (unofficial online mirror, Div. 1 only) B. Work Group 树形dp
题目链接: http://codeforces.com/problemset/problem/533/B B. Work Group time limit per test2 secondsmemor ...
- HDU 5875 Function 优先队列+离线
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5875 Function Time Limit: 7000/3500 MS (Java/Others) ...
- Jmeter 中JDBC request 详解 !
JDBC Request: 这个sampler可以向数据库发送一个jdbc请求(sql语句),它经常需要和JDBC Connection Configuration 配置元件一起配合使用. 目录: 一 ...
- mysql导出/导入表结构以及表数据
导出: 命令行下具体用法如下: mysqldump -u用戶名 -p密码 -d 数据库名 表名 脚本名; 1.导出数据库为dbname的表结构(其中用戶名为root,密码为dbpasswd,生成的脚 ...
- 【设计模式】C++中的单例模式
讲解来自:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&id=4281275&uid=26611383 由于使用了POSIX函 ...