catalog

1、面向对象

2、类的继承(续):直接继承与间接继承

3、类方法、静态方法、属性方法

4、getitem

5、反射

6、_new_\_metaclass_

7、异常处理

1、面向对象

面向对象编程
class类(新式类:class xx(obj):,经典类 class xx:) 构造函数 __init__(self,ret1,ret2...) 在实例化时做一些类的初始化工作
析构函数 __del__ (self): 在实例释放或销毁的时候,通常做一些收尾工作,如关闭打开的临时文件、关闭数据库等
类变量
实例变量(静态属性)
方法(动态属性) object对象
encapsulation 封装
私有方法
私有属性
Inheritance 继承
继承
继承、组合
多继承
python2x上
新式类 广度优先(从左到右,先走同级)
经典类 深度优先(竖向查询,先走最深级)
python3x上
都是广度优先
Polymorphism 多态
同一个接口多种实现 把一个类变成一个具体对象的过程叫实例化
实例想调用类里面的方法是把自己变成变量传给类,所以def(self)中的self即是定义的变量
实例变量的作用域就是实例本身
当实例变量与类变量名相同时,先找实例变量。

2、类的继承

 class People(object):
def __init__(self,name):
self.name = name
def talk(self):
print('%s is talking...'% self.name) p1 = People('alex') #直接继承
class Men(People):
def __init__(self,name,age)
super(Men,self).__init__(self,name)
self.age = age #间接继承
class Women(Object)
def __init__(self,name,obj)
self.name = name
self.people = obj
def talk(self):
print('This is inherit name [%s]'% self.people.name)
print('This is defined name[%s]'% self.name) w1 = Women('wtl',p1)
w1.talk() >>>>>>this is inherit name alex
>>>>>>this is defined name wtl

3、静态方法、类方法、属性方法

类方法:
@classmethod
只能访问类变量,不能访问实例变量 静态方法:
@staticmethod
静态方法,使该方法变为类下的一个函数,与类没什么太大关系 属性方法:
@property
@setter
@deleter
使一个方法变为属性
作用:隐藏过程细节,对客户友好。
特殊的运用:
def __call__(self,*args,**kwargs):#可以给实例传参数
  code
def __str__(self):#将值返回给实例的门牌号
  code
# print(Dog.__doc__) # __doc__输出类的描述信息
# print(Dog.__module__) # 描述类从哪里导入的
# print(Dog.__class__) #描述类本身
#
# print(Dog.__dict__) # 如果对象是类,打印类里面的所有属性,不包括实例属性
# print(d1.__dict__) # 如果对象是实例化对象,输出实例化对象的属性
 class People(object):
name = 'Jinx'
def __init__(self,name):
self.name = name
self.__obj =None @staticmethod #静态方法,传入完全不相干的参数
def eat(name,food):
print('%s is eating the %s'%(name,food))
@staticmethod #传入self,在调用时需要把自己传进去
def sleep(self):
pritn('%s is sleeping.....'% self.name) @classmethod#类方法,只能调用类的变量
def play(self):
print('%s is plaing...'% self.name) @property #属性方法
def cof(self):
print('%s is eating with %s'%(self.name,self.__obj)
@cof.setter
def cof(self,food):
print('%s want to eat %s'%(self.name,food))
self.__obj = food
@cof.deleter
def cof(self):
del self.__obj
print('删完了') def __call__(self,*args,**kwargs): #可以给实例后面跟参数
print('call running:',args,kwargs) def __str__(self): #给门牌号返回一个值
print('<obj>:',self.name) p = People('alex')
p.eat('Jinx','regou')
p.sleep(p)
p.play()
p.cof
p.cof = 'kaochang'
del p.cof
d(1,2,3,'age' = 22,'salary' = 10000)
print(d)

4、getitem、setitem、delitem

 class Dog(object):
'''描述狗的特性'''
name = 'right'
def __init__(self,name):
self.name = name
self.__obj = None
self.data = {} def __getitem__(self, key):
print('in the getitem:',key)
return self.data.get(key) def __setitem__(self, key, value):
print('Setitem:',key,value)
self.data[key] = value def __delitem__(self, key):
print('__delitem__',key) d1 = Dog('alex')
d1['age'] = 20
print(d1.data)

5、反射

setattr() # 创建方法

getattr() # 获取方法

delattr() # 删除方法  delattr(p,p.name)

 class People(object):
def __init__(self,name,age):
self.name = name
self.age = age
def talk(self):
print('%s is talking'% self.name) p = People('alex',20) def eat(self):
print('eating with %s'% self.name) choice = input('>>>:').strip() # 方法的反射
if hasattr(p,choice): #如果存在,则运行函数
getattr(p,choice)()
else: # 如果不存在,将一个已有的函数创建为方法
setattr(p,choice,eat) #把eat这个函数付给choice,新建了一个choice的方法。
getattr(p,choice)(d) #属性的反射
if hasattr(p,choice):
getattr(p,choice)
else:
setattr(p,choice,'rink') # choice为一个变量名,‘rink’为变量的值付给变量名
print(getattr(p,choice))

6、__new__ / __metaclass__

new方法,在创造实例的时候先于init实行。

必须要有return,这个return作用是:1、告诉要实例化的类  2、调用哪个类的new来实例化

参考:https://blog.csdn.net/ll83477/article/details/76419318

 class A(object):
def __new__(cls, *args, **kwds):
print("one")
print ("A.__new__", args, kwds)
return object.__new__(B)
def __init__(cls, *args, **kwds):
print("two")
print ("A.__init__", args, kwds)
class B(object):
def __new__(cls, *args, **kwds):
print("three")
print(cls)
print(B)
print("B.__new__", args, kwds)
return object.__new__(cls)
def __init__(cls, *args, **kwds):
print ('four')
print ("B.__init__", args, kwds)
class C(object):
def __init__(cls, *args, **kwds):
print ("five")
print ("C.__init__", args, kwds)
print(C())
print( "=====================")
print (A())
print ("=====================")
print (B())

7、异常处理

异常处理

写法一
try:
code
except Error1 as e:
print e
except Error2 as e:
print e
...
except Exception as e: #Exception(所有的预判情况)但是通常放在最后处理没有预判的情况
print(未知错误,e)
else: #else 当程序正常运行时进行的操作
print(一切正常...)
finaly: #finaly 不管程序异常与否都继续往下走
code 写法2:(不建议使用)
try:
code
except (Error1,Error2....) as f:
print e
else:
print(一切正常...)
finaly:
code
 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的 常用异常

常用异常

 a = 'alex'
b = [1,2,3]
tyr:
a[1]
b[10]
except KeyError as e:
print('关键字错误',e)
except ValueError as e:
print('值错误',e)
except Exception as e:
print('未知错误',e)
else:
print('go ahead')
finally:
print('不想理你')

抛出异常

 #1\
class SQError(Exception):
def __init__(self,msg):
self.mag = msg
try:
raise SQError('数据库处理错误')
except SQError as e:
print(e) #2\
# 自定义异常错误
class MyError(ValueError):
ERROR = ("-1", "没有该用户!") # 抛出异常测试函数
def raiseTest():
# 抛出异常
raise MyError(MyError.ERROR[0], # 异常错误参数1
MyError.ERROR[1]) # 异常错误参数2 # 主函数
if __name__ == '__main__':
try:
raiseTest()
except MyError as msg:
print("errCode:", msg.args[0]) # 获取异常错误参数1
print("errMsg:", msg.args[1]) # 获取异常错误参数2

week7的更多相关文章

  1. 个人博客作业week7

    个人阅读作业week7 一.瀑布 软件工程的瀑布模型是1970年由Winston Royce提出来的,即软件的开发按照一个严格的.顺序的.单次的瀑布流开发周期.例如需求分析阶段.概要设计阶段.详细设计 ...

  2. [阅读]个人阅读作业week7(200)

    个人作业week7——前端开发感想总结 此次作业因本人(学号1200)长期不上博客所以密码遗忘,输错次数过多账号被锁,所以在SivilTaram同学的博客下挂我的作业,希望助教老师谅解~谢谢! 1. ...

  3. Spark小课堂Week7 从Spark中一个例子看面向对象设计

    Spark小课堂Week7 从Spark中一个例子看面向对象设计 今天我们讨论了个问题,来设计一个Spark中的常用功能. 功能描述:数据源是一切处理的源头,这次要实现下加载数据源的方法load() ...

  4. week7 ls

    week7 ls 实现ls: 实现ls -l:

  5. 个人作业week7——前端开发感想总结

    个人作业week7——前端开发感想总结 1. 反思 首先要谈谈在这次团队项目的工作中,我这边出现过的较为严重的一个问题:我和HoerWing (后端担当)合作时,最初因为我没有使用github(始终连 ...

  6. Internet History, Technology and Security (Week7)

    Week7 With reliable "pipes" available from the Transport layer, we can build applications ...

  7. Internet History,Technology,and Security -Technology: Application Protocols(Week7)

    Week7 Technology: Application Protocols This week, we’ll be covering application protocols. With rel ...

  8. 个人阅读作业Week7

    没有银弹 <没有银弹>,Brooks在该论文中,强调真正的银弹并不存在,而所谓的没有银弹则是指没有任何一项技术或方法可以能让软件工程的生产力在十年内提高十倍.文中讨论到了软件工程中主要的两 ...

  9. week7 read

    对于银弹: 在<No Silver Bullet>这篇IBM大型电脑之父佛瑞德·布鲁克斯(Fred Brooks)在1987年所发表的一篇关于软体工程的经典论文中,强调了由于软件的复杂性本 ...

  10. [阅读]个人阅读作业week7

    People-oriented in Agile People-oriented in Agile One Leader Prepare Good ideas from users People-or ...

随机推荐

  1. Linux 开放端口号(mysql开启远程连接)

    在 Centos 7 或 RHEL 7 或 Fedora 中防火墙由 firewalld 来管理,而不是 iptables. 一.firewalld 防火墙语法命令如下:启用区域端口和协议组合 fir ...

  2. 第一章 Python程序语言简介

    第一节 Python概述 1. 什么是Python Python是一种 解释型.面向对象.动态数据类型 的高级程序设计语言.由Guido van Rossum与1989年发明,第一个公开发行版本发行于 ...

  3. CH 6201 走廊泼水节题解

    题目链接:CH6201 当时在海亮考试的第一题: 心得:其实一个算法是要真正理解这个思路和过程,而并不是单单知道它是用来写什么题的: 思路:n个节点有n-1条边,把这n-1条边按照权值从小到大排序,有 ...

  4. 国际空间站直播 ISS直播

    b站:https://live.bilibili.com/9196015 斗鱼:https://www.douyu.com/543816 欢迎大家 (ฅ´ω`ฅ)

  5. Host 'xxx' is not allowed to connect to this MySQL server.

    mysql开启远程连接 今天在服务器安装了mysql,准备用mysqlguitools远程登录的时候出错,提示:Host 'xxx' is not allowed to connect to this ...

  6. threadpool源码学习

    threadpool源码学习 __all__ = [ 'makeRequests', 'NoResultsPending', 'NoWorkersAvailable', 'ThreadPool', ' ...

  7. Redis 集群版

    1.# yum install ruby -y 1.1 后面需要用到ruby脚本 2.# yum install rubygems -y 1.1 安装ruby包管理器 3.# gem install ...

  8. 人生苦短,我用Python——博客目录

    计算机基础 计算机硬件基础知识 操作系统基础 Python基础 Windows环境下Python2和Python3的安装 交互式环境与变量的使用 简单介绍Python基本数据类型及程序交互 基本运算符 ...

  9. 微信小程序复选框实现 多选一功能

    功能实现界面 data: { checkboxItems: [ { name: '全天(1-8节)', value: 'allday' }, { name: '上午(1-4节)', value: 'a ...

  10. 清除控制台 console

    清除控制台 console.log(1) // console.clear() // CTRL + K // Ctrl + L // process.stdout.write('\033c'); // ...