琪齐

空想终日彷徨行动方可无惧!

导航

反射、面向对象(基础篇)

Posted on 2016-06-01 16:11  琪齐  阅读(760)  评论(0编辑  收藏  举报

反射

  通过字符串的形式,导入模块

  通过字符串的形式,去模块中寻找指定的函数,并执行

1、本质

  __import__  例:dd == __import__('commons')

  __import__("lib.commons.s1")  #这样只能导入到lib,不能导入到s1

  __import__("lib.commons.s1",fromlist=true)  #这样就能导入到s1

2、应用

 1 inp = input("请输入模块:" 2 
 3 inp_func = input("请输入要执行的函数:")
 4 
 5 print(inp,type(inp))
 6 
 7 dd = __import__(inp)  #__import__ 用于一字符串的形式导入模块
 8 
 9 target_func = getattr(dd,inp_func)  #在获取到函数名后加 () 表示执行函数
10 
11 result = target_func()
12 
13 print(result)

 

3、反射功能

不只是在模块中操作,根据字符串的形式去对象中操作成员(一切事物皆对象!)

  getattr()  根据字符串的形式去某个模块中寻找东西

  hasattr()  根据字符串的形式去某个模块中判断东西是否存在

  setattr()   根据字符串的形式去某个模块设置东西

  delattr()   根据字符串的形式去某个模块中删除东西

实例:

1 NAME = "alex"
2 def f1():
3     print("f1")
4     return "F1"
5 
6 def f2():
7     return "F2"
commons文件

 

 1 import commons
 2 
 3 target_func = getattr(commons,'NAME',None) #获取成员
 4 print(target_func)
 5 #target_func()
 6 
 7 r = hasattr(commons,'Aamse')  #在模块中查询输入的东西,查到返回True,查不到返回False
 8 print(r)
 9 
10 commons.f1()
11 r =hasattr(commons,'AGE')  #检查是否含有成员
12 print(r)
13 
14 setattr(commons,"AGE",lambda  a: a + 1)  #设置成员
15 r = hasattr(commons,'AGE')
16 print(r)
17 
18 delattr(commons,'NAME')  #删除成员
19 r = hasattr(commons,'NAME')
20 print(r)

访问一个对象的成员操作:

 1 class Foo(object):
 2     def __init__(self):
 3         self.name = 'alex'
 4         #print(self.name)
 5 
 6     def func(self):
 7         return "func"
 8 
 9 obj = Foo()
10 
11 obj.name  #访问字段
12 obj.func()  #执行方法
13 #详解:
14 #name和func是变量名
15 #obj.name表示去obj中或是类寻找变量名是name,并获取对应内存地址中的内容。
16 #**********
17 #用其他方式获取obj对象中的name变量指向内存中的值“alex”
18 class Foo(object):
19 
20     def __init__(self):
21         self.name = 'alex'
22 
23 obj = Foo()
24 #法一:
25 # class Foo(object):
26 #
27 #     def __init__(self):
28 #         self.name = 'alex'
29 #
30 #     def func(self):
31 #         return 'func'
32 #
33 
34 # obj = Foo()
35 #
36 # print(obj.__dict__['name'])
37 #法二:
38 class Foo(object):
39 
40     def __init__(self):
41         self.name = 'alex'
42 
43     def func(self):
44         return 'func'
45 
46 
47 obj = Foo()
48 
49 print(getattr(obj, 'name'))
View Code

 

 

Web框架实例

def login():
    return "login"

def logout():
    return "logout"

def nb():
    return "特别牛逼页面"
lib下acccount文件

 

def f1():
    return "添加订单"
lib下manager文件

 

def f2():
    return "加入购物车"
lib下orderr文件

 

用下面调用:

 1 #基础调用
 2 # from lib import acccount
 3 #
 4 # url = input('请输入url: ')
 5 # if url.endswith('login'):
 6 #     r = acccount.login()
 7 #     print(r)
 8 # elif url.endswith('logout'):
 9 #     r = acccount.login()
10 #     print(r)
11 # elif url.endswith('nb'):
12 #     r = acccount.nb()
13 #     print(r)
14 # else:
15 #     print("404")
16 #**************************
17 #用反射写如下:
18 # from lib import acccount
19 #
20 #
21 # url = input('请输入URL:')
22 # inp = url.split('/')[-1]
23 # if hasattr(acccount,inp):
24 #     target_func = getattr(acccount,inp)
25 #     r = target_func()
26 # else:
27 #     print("404")
28 #****************************
29 #动态的调用
30 url = input('请输入URL:')
31 
32 target_module,target_func = url.split('/')
33 
34 m = __import__("lib."+target_module,formlist=True)
35 
36 if hasattr(m,target_func):
37     target_func = getattr(m,target_func)
38     r = target_func()
39     print(r)
40 else:
41     print("404")

 

面向对象

c#、Java:  只能面向对象编程

Ruby、Python: 函数编程 + 面向对象编程

一,面向过程编程

二,面向对象编程,类,def 函数

1 def fetch(backend):
2     pass
3 
4 def add_record(backend, record):
5     pass
6 
7 fetch("www.oloboy.org")
8 add_record("www.oloboy.org",xxxxx)

 

三,面向对象式编程,def 函数

 1 class Oldboy:
 2 
 3     def fetch(self,backend):
 4         pass
 5 
 6     def add_record(self,backend):
 7         pass
 8 
 9 obj = Oldboy()
10 obj.fetch("www.oloboy.org")
11 obj.add_record("www.oloboy.org",xxxxx)

 

 

1,面向对象不是所有情况都适用

2,面向对象编程

a.定义类

class Foo:
    def 方法1(self,bb):
        pass

 

b,根据类创建对象(创建一个Foo类实例)

  使用对象去执行类中的方法

 1 class Oldboy:
 2 
 3     def fetch(self,backend):
 4         print(backend)
 5 
 6     def add_record(self,backend,record):
 7         pass
 8 
 9 
10 obj = Oldboy()  #创建对象
11 obj.fetch("bbb")

 

3,self,形式参数,代指执行方法的对象。python内部传递。

1 class Oldboy:
2     def fetch(self,backend):
3         print(backend,self)  #<__main__.Oldboy object at 0x0000000000D44630>
4 
5 obj = Oldboy()
6 print(obj)
7 obj.fetch("bbb")  #bbb <__main__.Oldboy object at 0x0000000000D44630>

 

4,类+括号  

自动执行类中的__init__方法;创建了一个对象

 1 class Foo:
 2     def __init__(self,name,age):  #称为构造方法,根据创建对象时自动执行
 3         self.name = name
 4         self.age = age
 5 
 6 #根据类Foo创建对象
 7 #自动执行Foo类的__init__方法
 8 obj1 = Foo('fen',45)  #将fen和45分别封装到name和age属性中
 9 
10 #根据类Foo创建对象
11 #自动执行Foo类的__init__ 方法
12 obj2 = Foo(’gen',80)#将gen和80分别封装到name和age属性中

 

在__init__方法中执行具体封装的操作 

__init__ 有一个特殊的名字:构造方法

__init__作用:1,创建对象;2,封装

 1 class Oldboy:
 2     def __init__(self,bk):  #bk是形参,对应外部传过来的实参
 3         """
 4         构造方法
 5         :param bk:
 6         
 7         """
 8         self.backend = bk  #普通字段;self.backend = bk相当于在__init__中bk的参数
 9 
10     def fetch(self):  #方法
11         print(self.backend)  #backend用来接收init方法中bk的参数
12 
13     def add_record(self,record):
14         print(self.backend)
15 
16     def del_record(self):
17         print(self.backend)
18 
19 obj1 = Oldboy("www.oldboy.org")  #创建对象obj1并且将"www.oldboy.org"封装在对象中
20 
21 #obj1.backend = "www.oldboy.org"  #封装一种方式;在对象中封装数据
22 
23 obj1.del_record()  #执行方法,执行过程中可以根据self去obj1中去取已经封装在里面的数据

 

 

 

面向对象三大特性

1,封装

使用场景:当同一类型的方法具有相同参数时,直接封装到对象即可。
使用场景:把类当做模板,创建多个对象(对象内封装的数据可以不一样)

 1 class Oldboy:
 2 
 3     def fetch(self):
 4         print(self.backend)
 5 
 6     def add_record(self,record):
 7         print(self.nackend)
 8 
 9     def del_record(self):
10         print(self.backend)
11 
12 #创建对象实例
13 obj1 = Oldboy()
14 obj1.backend = "www.oldboy.org"  #在对象中封装数据
15 obj1.fetch()
16 
17 obj2 = Oldboy()
18 obj2.backend = "www.oldboy.org"
19 obj2.fetch()  #执行方法,执行过程中可以根据self去obj1中去取已经封装在里面的数据。

 

实例:

 1 class Person:
 2     def __init__(self,name,age,weight):
 3         self.Name = name
 4         self.Age = age
 5         self.Weight = weight
 6 
 7     def chi(self):
 8         self.Weight = self.Weight + 2
 9         print(self.Weight)
10 
11     def jianshen(self):
12         self.Weight = self.Weight - 1
13         print(self.Weight)
14 
15 o1 = Person('小明', 5,200)
16 o1.jianshen()
17 o1.chi()
18 o1.chi()
19 o1.chi()

 

 

2,继承

派生类继承基类

python2.7 多继承:
  未继承object(经典类):
      一条道走到黑(深度优先)
  继承object(新式类):
      顶部最后(广度优先)

python3.5 多继承:
      顶部最后

 

派生类和基类同时存在,优先找派生类
python类中可以继承多个,优先自己,再从左至右继承

用上述图阐述下面继承关系

 1 class Animals:  #基类(父类)
 2 
 3     def chi(self):
 4         print(self.name + "")
 5 
 6     def he(self):
 7         print(self.name + "")
 8 
 9     def piao(self):
10         print("buai")
11 
12 class Uncle:
13     def du(self):
14         print("")
15 
16     def piao(self):
17         print("1212")
18 
19 class Dog(Animals,Uncle):  #派生类(子类)
20     def __init__(self,name):
21         self.name = name
22 
23     # def piao(self):
24     #     print("ai")
25 
26     def jiao(self):
27         print(self.name + "")
28 
29 
30 alex = Dog("李杰")
31 alex.chi()
32 alex.he()
33 alex.jiao()
34 alex.piao()

 

 

多次继承

用图形阐述继承顺序

 1 class Alex(object):
 2     def f1(self):
 3         print("Alex")
 4 
 5 class A(Alex):
 6     def f(self):
 7         print("A")
 8 
 9 class B(Alex):
10     def f1(self):
11         print("B")
12 
13 class C(A):
14     def f(self):
15         print("C")
16 
17 class D(B):
18     def f1(self):
19         print("D")
20 
21 class E(C,D):
22     def f(self):
23         print("E")
24 
25 obj = E()
26 obj.f1()

 重点示例:

用上述图阐述(每次都是从最底层开始找)

首先从自身找,自身没有开始从A找;如果A找不到,再从C找;如果C中再找不到,再到B中找;

 1 class A:
 2     def bar(self):
 3         print('BAR')
 4         self.f1()
 5 
 6 class B(A):
 7     def f1(self):
 8         print('B')
 9 
10 class C:
11     def f1(self):
12         print('C')
13 
14 class D(C,B):  #主要self指向谁,就执行谁
15     pass
16 
17 d1 = D()  #输出BAR
18 d1.bar()  #输出C

 

 2.7的多继承

 

3,多态

多种形态
Python本身支持多态

 

 

*更加详细参考:http://www.cnblogs.com/wupeiqi/p/4493506.html

                       http://www.cnblogs.com/wupeiqi/articles/5017742.html