面向对象的好处

更容易扩展、提高代码使用效率,使你的代码组织性更强,

更清晰,更适合复杂项目的开发

封装

把功能的实现细节封装起来,只暴露调用接口

继承

多态

接口的继承

定义

类   ===> 模版

对象===> 实例化的类

属性

私有属性    __private

公有属性    存在类的内存里,所有实例共享

成员属性    ===>实例变量

方法  ==>函数

构造函数

析构函数:实例被销毁(手动删除实例的变量,或者程序结束)的时候,自动执行,

新式类

object

super(Myclass,self).__init__(...)

多继承  继承路径

广度优先

经典类

class Dog:

parent_class.__init__(self....)

深度优先

抽象接口

在子类定义一个需要写的接口,如果子类接口不写,就报父类定义的报错。

class Alert(object):
    def send(self):
        '''报警消息发送接口'''
        raise NotImplementedError

class MailAlert(Alert):
    # pass
    def send(self,msg):
        print("----sending...",msg)

m = MailAlert()
m.send('fd')

静态方法&类方法&属性方法

class Person(object):
    name='rain'
    def __init__(self,name):
        self.name=name

    @staticmethod
    def eat(name,food):#静态方法既不能访问公有属性,也不能访问实例属性
        print("%s is eating %s"%(name,food))

    @classmethod
    def walk(self): #类方法,只能访问类的公有属性,不能访问实例属性
        print("%s is walking"%self.name)

    @property  #属性方法,作用是把一个方法变成一个静态属性
    def talk(self):
        print("%s says"%self.name)

    @talk.setter  #修改属性
    def talk(self,msg):
        print("set msg:",msg)

    @talk.deleter  #删除属性
    def talk(self):
        print("delete talk...")

p=Person("Jack")
Person.eat("Jack","apple")
Person.walk()
p.talk
p.talk="hello"
del p.talk

以上代码运行结果

Jack is eating apple
rain is walking
Jack says
set msg: hello
delete talk...

类的特殊成员方法

1. __doc__  表示类的描述信息

2. __module__ 和  __class__ 

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

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

class Flight(object):
    '''Flight status checking'''
    def __init__(self,name):
        self.flight_name = name

    def checking_status(self):
        print("checking flight %s status " % self.flight_name)
        return  1

    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0 :
            print("flight got canceled...")
        elif status == 1 :
            print("flight is arrived...")
        elif status == 2:
            print("flight has departured already...")
        else:
            print("cannot confirm the flight status...,please check later")

    @flight_status.setter
    def flight_status(self,status):
        print("flight status is %s"%status)

f = Flight("CA980")
print(f.__doc__)
print(f.__module__)
print(f.__class__)

以上代码运行结果

Flight status checking
__main__
<class '__main__.Flight'>

3. __init__ 构造方法,通过类创建对象时,自动触发执行。

4.__del__

 析构方法,当对象在内存中被释放时,自动触发执行。

注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的

5. __call__ 对象后面加括号,触发执行。

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

6. __dict__ 查看类或对象中的所有成员   

7.__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。

class Foo:

    def __str__(self):
        return 'alex li'

obj = Foo()
print (obj)
# 输出:alex li

8.__getitem__、__setitem__、__delitem__

用于索引操作,如字典。以上分别表示获取、设置、删除数据

class Flight(object):
    def __init__(self,name):
        self.flight_name = name
        self.__status=None

    def checking_status(self):
        print("checking flight %s status " % self.flight_name)
        return  1

    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0 :
            print("flight got canceled...")
        elif status == 1 :
            print("flight is arrived...")
        elif status == 2:
            print("flight has departured already...")
        else:
            print("cannot confirm the flight status...,please check later")

    @flight_status.setter
    def flight_status(self,status):
        self.__status=status
        print("changed status to %s"%self.__status)

    def __call__(self, *args, **kwargs):
        print("__call:",args,kwargs)

    def __str__(self):
        return "<flight:%s,status:%s>"%(self.flight_name,self.__status)

    def __getitem__(self, item):
        print("get item",item)
        return 22
    def __setitem__(self, key, value):
        print("set key",key,value)
    def __delitem__(self, key):
        print("deleteing",key)

f = Flight("CA980")
f()         #__call__
print(f)    #__str__
print(f["age"])         #__getitem__
f["age"]=26         #__setitem__
del f["age"]        #__delitem__

以上代码输出结果

__call: () {}
<flight:CA980,status:None>
get item age
22
set key age 26
deleteing age

9、__module__

以字符串的形式导入模块

F:\zhou\python\day8\flight_status.py内容如下

class Flight(object):
    '''Flight status checking'''
    def __init__(self,name):
        self.flight_name = name

    def checking_status(self):
        print("checking flight %s status " % self.flight_name)
        return  1

    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0 :
            print("flight got canceled...")
        elif status == 1 :
            print("flight is arrived...")
        elif status == 2:
            print("flight has departured already...")
        else:
            print("cannot confirm the flight status...,please check later")

    @flight_status.setter
    def flight_status(self,status):
        print("flight status is %s"%status)

f = Flight("CA980")

实例

mod=__import__('day8.flight_status',fromlist=True)
print(mod)
f=mod.Flight('CA980')
# print(f)
f.flight_status

以上代码运行结果

<module 'day8.flight_status' from 'F:\\zhou\\python\\day8\\flight_status.py'>
checking flight CA980 status
flight is arrived...

10. __new__ \ __metaclass__

class Foo(object):

    def __init__(self,name):
        self.name = name

f = Foo("alex")

print(type(f))
print(type(Foo))

以上代码运行结果

<class '__main__.Foo'>
<class 'type'>

上述代码中,obj 是通过 Foo 类实例化的对象,其实,不仅 obj 是一个对象,Foo类本身也是一个对象,因为在Python中一切事物都是对象

f对象是Foo类的一个实例Foo类对象是 type 类的一个实例,即:Foo类对象 是通过type类的构造方法创建。

创建类有两种方式:

1)普通类

class Foo(object):

    def func(self):
        print 'hello alex'

2)特殊方式

def func(self):
    print 'hello wupeiqi'

Foo = type('Foo',(object,), {'func': func})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员

实例

def talk(self,msg):
    print("%s is talking:%s"%(self,msg))
Dog=type("Dog",(object,),{"talk":talk})
print(type(Dog))
d = Dog()
d.talk("efdsd")

def talk(self,msg):
    print("%s is talking:%s"%(self.name,msg))
def __init__(self,name):
    self.name=name
Dog=type("Dog",(object,),{"talk":talk,"__init__":__init__})
print(type(Dog))
d = Dog("Haitao")
d.talk("efdsd")
Dog.talk

以上代码运行结果

<class 'type'>
<__main__.Dog object at 0x000002A339552668> is talking:efdsd
<class 'type'>
Haitao is talking:efdsd

__metaclass__

__metaclass__可以设置一个类的派生类,来查看类创建的过程。

class MyType(type):
    def __init__(self, child_cls, bases=None, dict=None):
        print("--MyType init---", child_cls,bases,dict)
        #super(MyType, self).__init__(child_cls, bases, dict)

    # def __new__(cls, *args, **kwargs):
    #     print("in mytype new:",cls,args,kwargs)
    #     type.__new__(cls)
    def __call__(self, *args, **kwargs):
        print("in mytype call:", self,args,kwargs)
        obj = self.__new__(self,args,kwargs)

        self.__init__(obj,*args,**kwargs)

class Foo(object,metaclass=MyType): #in python3
    # __metaclass__ = MyType #in python2

    def __init__(self, name):
        self.name = name
        print("Foo ---init__")

    def __new__(cls, *args, **kwargs):
        print("Foo --new--")
        return object.__new__(cls)

    def __call__(self, *args, **kwargs):
        print("Foo --call--",args,kwargs)
# 第一阶段:解释器从上到下执行代码创建Foo类
# 第二阶段:通过Foo类创建obj对象
obj = Foo("Alex")
# print(obj.name)

异常处理

1、基本结构

2、复杂结构

3、异常对象

  try:

    代码块

    代码块

    代码块

    代码块

  except Exception as obj:

    obj对象中封装了当前触发的错误信息

    ...(将错误信息写入数据库)

  class Message:

    def __init__(self,name):

      self.name=name

  obj=Message('ssss')

4、异常种类

Exception能将所有的异常都捕获

其它        只能处理某一种情况

try:

  代码块

  代码块

  代码块

except ValueError as obj:

  pass

except KeyError as obj:

  pass

5、主动触发异常

  raise Exception('邮件发送失败')

  def execute():
  try:

    result = foo1()
    if result:
      pass
    else:
      raise Exception('邮件发送失败')
    foo2()
  exception Exception as e:

    #记录日志

6、断言

如果条件不成立,直接抛异常

print(1)
assert 1!=1

print(2)

以上代码运行结果

Traceback (most recent call last):
1
  File "F:/zhou/python/day8/断言.py", line 6, in <module>
    assert 1!=1
AssertionError

7、自定义异常处理

class HaiTaoError(Exception):
    def __init__(self, message):
        self.msg = message
        super(HaiTaoError, self).__init__(message)

try:
    name="alex"
    if name != "haitao":
        raise HaiTaoError('fffff')
except IndexError as e:
    print(e,e.msg)
except Exception as e:
    print(e,1111)

以上代码运行结果

fffff 1111

8、反射

1)允许用户输入

    account/login

    account/logout

    home/index

    home/order

2)看到不同的结果

3)404

li=[account/login,account/logout,home/index,home/order]

inp=input('>>')

 
hashattr(容器,'名称')    #以字符串的形式判断某个对象中是否含有指定的属性
getattr(容器,'名称')       #以字符串的形式获取某个对象中指定的属性
setattr(容器,'名称')       #以字符串的形式设置某个对象中指定的属性
delattr(容器,'名称')       #以字符串的形式删除某个对象中指定的属性

方法一:

from controller import account

action=input('>>')
if (hasattr(account,action)):
    v= getattr(account,action)
    result=v()
else:
    result='
print(result)

方法二:

inp=input('请输入url>>:')

m,n= inp.split('/')

from controller import account

func=getattr(account,n)
result=func()
print(result)

方法三(导入多个py文件):

inp=input('请输入url>>:')
m,n= inp.split('/')
mod= __import__('controller.%s'%m,fromlist=True)
func=getattr(mod,n)
result=func()
print(result)

最终完整版:

while True:
    try:
        inp=input('请输入url>>:')
        m,n= inp.split('/')
        mod= __import__('controller.%s'%m,fromlist=True)
        if hasattr(mod,n):
            func=getattr(mod,n)
            result=func()
        else:
            result=404
    except Exception as e:
        result=500
    print(result)

反射本质上是到某个对象中找东西

python基础八的更多相关文章

  1. python基础(八)面向对象的基本概念

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 谢谢逆水寒龙,topmad和Liqing纠错 Python使用类(class)和对 ...

  2. Python基础 — 八种数据类型

    Python 3.x 的八种数据类型 八种数据类型分别是: number(数字).string(字符串).Boolean(布尔值).None(空值) list(列表).tuple(元组).dict(字 ...

  3. python基础(八)生成器,迭代器,装饰器,递归

    生成器 在函数中使用yield关键字就会将一个普通的函数变成一个生成器(generator),普通的函数只能使用return来退出函数,而不执行return之后的代码.而生成器可以使用调用一个next ...

  4. Python基础(八) yaml在python中的使用

    yaml 通常用来存储数据,类似于json YAML 简介 YAML(Yet Another Markup Language),一种直观的能够被电脑识别的数据序列化格式,是一个可读性高并且容易被人类阅 ...

  5. Python基础(八) 模块的引入与定义

    模块定义 什么是模块:一个py文件就是一个模块 模块分为三类: 内置模块,(标准库):.python解释器自带的,time,os,sys,等等.200多种. 自定义模块:自己写的模块 第三方库(模块) ...

  6. python基础八之文件操作

    python的文件操作 1,打开文件 编码方式要和文件的编码方式相同! #open('路径','打开方式','指定编码方式') f = open(r'E:\pycharm\学习\day8\test', ...

  7. python基础八---文件操作

    1.文件操作 XXXXX.txt 1.文件路径:d:\XXXXX.txt(绝对路径) 2.编码方式:utf-8 gbk 3.操作方式:只读.只写.追加.读写.写读.... 排错: 以什么编码方式储存的 ...

  8. python 基础(八) os模块

    OS模块 概念:包含了普遍的操作 系统的功能 一.函数 函数名 函数说明 os.name 获取操作系统类型 nt->Windows posix->Linux/Unix os.listdir ...

  9. 十八. Python基础(18)常用模块

    十八. Python基础(18)常用模块 1 ● 常用模块及其用途 collections模块: 一些扩展的数据类型→Counter, deque, defaultdict, namedtuple, ...

随机推荐

  1. [LeetCode] Roman to Integer 罗马数字转化成整数

    Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 t ...

  2. 写出将字符串中的数字转换为整型的方法,如:“as31d2v”->312,并写出相应的单元测试,正则去掉非数值、小数点及正负号外的字符串

    写出将字符串中的数字转换为整型的方法,如:"as31d2v"->312,并写出相应的单元测试,输入超过int范围时提示不合法输入. public struct Convert ...

  3. C-RAN 集中化、协作化、云化、绿色节能(4C)

    中国移动C-RAN力拼第4个C:2018年6月外场组网验证 http://www.c114.net ( 2016/11/22 07:41 ) C114讯 11月22日早间消息(子月)2009年,中国移 ...

  4. 使用AccessibilityService执行开机自启动

    res/xml/accessibility_service_config.xml <accessibility-service xmlns:android="http://schema ...

  5. 在 Sublime Text 3 中配置编译和运行 Java 程序

    参考网址:http://www.open-open.com/lib/view/open1388105023765.html 1. 设置 java 的 PATH 环境变量 2. 创建批处理或 Shell ...

  6. jQuery 事件方法

    事件方法触发器或添加一个函数到被选元素的事件处理程序. 下面的表格列出了所有用于处理事件的 jQuery 方法. 方法 描述 bind() 向匹配元素附加一个或更多事件处理器 blur() 触发.或将 ...

  7. StringTokenizer类的使用

    StringTokenizer是一个用来分隔String的应用类,相当于VB的split函数. 1.构造函数 public StringTokenizer(String str) public Str ...

  8. 神经网络与深度学习(3):Backpropagation算法

    本文总结自<Neural Networks and Deep Learning>第2章的部分内容. Backpropagation算法 Backpropagation核心解决的问题: ∂C ...

  9. Javascript模板引擎插件收集

    为什么要用JS的模板引擎,打个比方,如果你要通过接口绑定数据,最终要加进去DOM中,我们普遍的做法就是不断的+,最终append进去,但是这样的做法就是后续人员压根就没法维护.所以这时模板引擎出来了. ...

  10. CentOS 7网卡网桥、绑定设置

    一.网卡桥接设置: 1.网卡配置文件: [root@localhost /]# vim /etc/sysconfig/network-scripts/ifcfg-enp8s0 TYPE=Etherne ...