python study to 8 基础篇

面向对象的三大特性--多态

多态(多种类型、多种形态):在面向对象编程中,类方法中所传的形式参数的各种基本数据类型。

python面向对象编程中的多态特性中的类方法中的参数可以是python中的任意基本数据类型,在python多态特性中类方法参数的基本数据类型不作区分。

在python面向对象多态中,函数参数传递可以支持多个多种类型,不区分哪种类型数据

例如:

def func(arg,kwargs):
       print(arg)
func(123)
func("","")
func(arg,kwargs)
func([1

C#/JAVA面向对象编程中,在调用类1,22,33,44])方法时,方法参数传递的基本数据类型,只支持类方法中定义的形式参数基本数据类型,不支持其他数据类型。

例如:

def func(int arg):#init 类型
    print(arg)
func(123)
func("alex") #报错,只支持init 参数!

class A:
   pass
class B(A):
   pass
calss C(A):
    pass
#arg 参数:必须是A类型或者是A派生子类型
def func(A arg):
 print(arg)
 obj = B()
 obj = C()
 obj = A()
 func(obj)

面向对象中的类成员

面向对象类成员分为三种:字段、方法、属性

1、字段

字段分为:普通字段(或者又叫动态字段)和静态字段

普通字段封装(保存)在对象中

例如:

class Foo:
    def __init__(self):
        self.name = "jack" #name即为普通字段
        
    def show(self):
        print(self.name)
obj = Foo()

静态字段封装(保存)在类中

例如:

 1 class province:
 2     country = "中国" #country即为类的静态字段
 3 
 4     def __init__(self,name):
 5         self.name = name
 6 
 7     def show(self):
 8         # print(self.name)
 9         print(123)
10 hn = province("河南")
11 hb = province("河北")
12 sd = province("山东")
静态字段

普通字段和静态字段的访问方式

 1 class province:
 2     country = "中国"
 3 
 4     def __init__(self,name):
 5         self.name = name
 6 
 7     def show(self):
 8         # print(self.name)
 9         print(123)
10 hn = province("河南")
11 # 一般情况下:自己访问自己
12 # 规则:普通字段只能使用对象去访问;静态字段使用类访问(万不得已的时候对象可以访问静态字段)
13 print(hn.name)#对象访问普通
14 print(province.country)#类访问静态字段
15 print(hn.country) #通过对象访问静态字段(万不得已的时候使用使用对象访问静态字段。)
普通字段和静态字段的访问方式

2、方法

面向对象成员方法中分为三种:普通方法、静态方法、类方法        

普通方法:普通方法,由对象去调用执行(方法属于类)

Class Province:
   Country = “中国”
   #普通方法
   def __init__(self,name):
       self.name = name
obj = Province(“河南”)
obj.show()

静态方法:由类调用执行。(当方法内部不需要对象中封装的值对,可以将方法写成静态方法)

class province:

@staticmethod
def f1(arg1,args2): #1、静态方法没有self:2、加上@staticmethod装饰器
    print(arg1,args2)

province.f1(111,222)

类方法:由类调用执行

class province:


    @classmethod
    def f2(cls): #cls 是类名, cls加()创建对象
        print(cls)
province.f2() #使用类名调用方法。

面向对象:普通方法、静态方法、类方法

 1 Class Province:
 2    Country = “中国”
 3    #普通方法
 4    def __init__(self,name):
 5        self.name = name
 6 
 7 @staticmethod
 8 def f1(arg1,args2)
 9 print(arg1,args2)
10        
11    @classmethod
12    def f2(cls):
13         print(cls)
14 
15 
16 obj = Province(“河南”)
17 obj.show()
18 
19 province.f1(111,222)
20 
21 province.f2()
View Code

3、属性

属性:使用字段访问方法的形式

 1 class Pager:
 2     def __init__(self,all_count):
 3         self.all_count = all_count
 4 
 5 
 6 @property
 7     def all_pager(self):
 8         a1, a2 = divmod(self.all_count,10)
 9         if a2 == 0:
10             return a1
11         else:
12             return a1 + 1
13 @all_pager.setter  #设置属性
14 def all_pager(self,value):
15             print(value)
16 
17 
18 @all_pager.deleter  #删除属性
19 def all_pager(self):
20            print("del all_pager")
21 
22 p = Pager(101)
23 # p.all_count #字段访问
24 # result = p.all_pager() #方法访问
25 # print(result)
26 
27 ret = p.all_pager  #获取数据
28 print(ret)
29 
30 p.all_pager = 111 #重新赋值,程序自动执行上面的方法。
31 
32 del p.all_pager   #程序自动执行删除程序的方法。
属性1
 1 class Pager:
 2     def __init__(self,all_count):
 3         self.all_count = all_count
 4 
 5     def f1(self):
 6         return 123
 7 
 8     def f2(self):
 9         pass
10 
11     def f3(self):
12         pass
13 
14     foo = property(fget=f1,fset=f2,fdel=f3)
15 
16 p = Pager(101)
17 result = p.foo #获取数据 执行fget
18 print(result) #
19 
20 p.foo = "alex" #重新赋值 执行fset
21 
22 del p.foo  #删除 执行fset
属性2

成员修饰符

面向对象成员分为:公有成员、私有成员

1、私有字段

定义私有字段(普通字段和静态字段)或者私有方法(普通方法、静态方法、类方法)需要在字段名称或者方法名称前加两个下划线。

普通私有字段

class foo:
def __init__(self,name):
     self.__name = name
					
def f1(self):
     print(self.__name)

obj = foo("alex")
print(obj.__name) #无法访问类中的私有字段

静态私有字段

class foo:
    __cc = "123"
    def __init__(self,name):
        self.name = name

    def f1(self):
        print(self.name)

    def f2(self):
       print(foo.__cc)

obj = foo("jack")
obj.f2()

# print(foo.__cc)

私有字段的继承关系

class foo:
def __init__(self,name):
     self.__name = name
					
def f1(self):
     print(self.__name)

class bar(foo):
    def f2(self):
        print(self.name)

obj = bar("jack") 
obj.f2() #私有字段通过继承的方式也无法被调用
obj.f1() #可以被调用

2、私有方法

普通私有方法

class foo:
    def __init__(self,name):
        self.__name = name

    def __f1(self):
        print(self.__name)

    def f2(self):
        obj.__f1()
obj = foo("alex")
# obj.__f1() #私有方法在外部不能被调用
# obj.f2()  #私有方法在内部调用可以被调用
# obj._foo__f1() #不到万不得已不要使用此方式调用私有字段

静态私有方法

class province:
    @staticmethod
    def __f1():
        print("welcome to beijing")

    def f2(self):
        province.__f1()

obj = province()
obj.f2() #间接内部访问静态私有方法可以被调用。
# province.f1() #外部不能直接访问静态私有方法。

特殊成员

构造方法和析构方法:

1 class foo:
2 #构造方法 创建对象时自动执行 __init__(self)方法
3     def __init__(self):
4         Pass
5     #析构方法
6     def __del__(self):
7         pass
构造方法和析构方法

 1、__doc__用于描述文档信息

1 class foo:
2     """
3     __doc__:用户描述文档信息
4     """
5     def func(self):
6         pass
7 
8 print(foo.__doc__)
__doc__

 2、__class__ 判断对象属于哪个类

1 class foo:
2     def func(self):
3         pass
4 obj = foo()
5 print(obj.__class__)
__class__

3、判断对象在哪个模块中 

1 from lib.s3 import foo
2 obj = foo()
3 # print(obj.__class__)
4 print(obj.__module__)
__module__

 4、__init__ 构造方法,创建对象时自动执行构造方法

1 class foo:
2 def __init__(self,name):
3         self.name = name
4         
5 obj = foo()
__init__

 5、__call__:对象后面加括号,触发执行

 1 注:构造方法的执行是由创建对象触发的,即:对象 = 类名();而对于__call__方法的执行是对象后加括号触发的,即:对象() 或者 类()()
 2 class foo:
 3 def __init__(self):
 4         pass
 5 
 6 def __call__(self, *args, **kwargs):
 7      print( "__call__(self, *args, **kwargs)")
 8 obj =foo()
 9 obj()
10 foo()()
__call__

 6、__str__:如果类中定义了__str__方法,在打印对象时,默认输出__str__方法中的返回值

 1 class foo:
 2 def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5 
 6 def __str__(self):
 7    return "%s——%d" %(self.name,self.age) #字符串拼接
 8 obj1 = foo("eric",19)
 9 obj2 = foo("jack",20)
10 print(obj1)
__str__

 7、__add__:当类中定义了__add__,在执行两个类相加时,自动返回__add__方法中返回值。

 1 class foo:
 2 def __init__(self,name,age):
 3      self.name = name
 4      self.age = age
 5 
 6 
 7 def __add__(self, other):
 8   return "%s——%d" %(self.name,other.age)
 9 
10 obj1 = foo("eric",19)
11 obj2 = foo("jack",20)
12 ret = obj1 + obj2
13 print(ret)
__add__

 8、__dict__:获取类和对象中的所有成员 (默认存在的)

 1 class foo:
 2 def __init__(self,name,age):
 3     self.name = name
 4     self.age = age
 5 
 6 def __add__(self, other):
 7     return "%s——%d" %(self.name,other.age)
 8 
 9 obj1 = foo("eric",19)
10 obj2 = foo("jack",20)
11 ret = obj1.__dict__
12 result = foo.__dict__
13 print(ret)
14 print(result)
__dict__

 9、class foo: __getitem__、__setitem__、__delitem__ 面向对象中通过对象操作字典的方式  (重要:自定义session框架使用)

 1 def __init__(self,name,age):
 2         self.name = name
 3         self.age = age
 4 
 5 
 6 def __getitem__(self, item):
 7         print("item")
 8         return 123
 9 
10 def __setitem__(self, key, value):
11         print("setitem")
12        
13 def __delitem__(self, key):
14         print("__delitem__")
15 
16 obj1 = foo("jack",19)
17 #dic = {"k1":123}  #dic = dict(k1=123)定义一个字典
18 #dic["k1"] #dic() #通过key 取value值
19 #dic["k1"] = 123  #给key 重新赋值
20 #del dic["k1"]  #删除字典中的键值对(key,value)
21 
22 obj1["ad"] #自动执行__getitem__
23 
24 obj1["k1"]=111 #自动执行__setitem__
25 
26 del obj1["k1"] #自动执行__delitem__
27 
28 
29 切片:python切片中也是调用的__getitem__、__setitem____delitem__方法
30 class foo:
31 def __init__(self,name,age):
32         self.name = name
33         self.age = age
34 
35 def __getitem__(self, item):
36         print(type(item))
37 
38 def __setitem__ (self, key, value):
39       print(type(key),type(value))
40 
41 def __delitem__(self, key):
42         print(type(key))
43 obj1 = foo("jack",19) 
44 ret2 = obj1[1:4:2]
45 obj1[1:4] = [11,22,33,44] 
46 del obj1[1:4]
__getitem__、__setitem__、__delitem__

 10、面向对象中迭代一个对象,需要使用iter方法

1 class foo:
2 def __iter__(self):#当一个对象放到for循环中,默认执行对象所在类的iter方法,生成器返回值给对象后,此对象可以被迭代
3     yield 1
4     yield 2
5 obj = foo()
6 for item in obj:
7 print(item)
__iter__

 面向对象中其他

1、isinstance判断一个对象是否在一个类中

class foo:
pass

obj = foo()
print(isinstance(obj,foo))

2、issubclass 判断一个类是否已另一个类的子类

class bar:
pass
class foo(bar):
    pass

print(issubclass(foo,bar))

3、执行父类的方法

class C1:
def f1(self):
        print("c1.f1")

class C2(C1):
def f1(self):
    主动执行父类中的方法
        super(C2,self).f1()
        #或者C1.f1(self)
        # print("c2.f1")

obj = C2()
obj.f1()

4、有序字典

class MyDict(dict):

def __init__(self):
        self.li = []
        super(MyDict, self).__init__()

def __setitem__(self, key, value):
        self.li.append(key)        super(MyDict,self).__setitem__(key,value)

 def __str__(self):
        temp_list = []
        for key in self.li:
             value = self.get(key)
             temp_list.append("'%s':%s" %(key,value))
             temp_str ="{"+",".join(temp_list)+"}"
        return temp_str

obj = MyDict()
obj["k1"]=123
obj["k2"]=456
print(obj)

设计模式之单例模式

单例模式:用来创建单个实例

class foo:
    instance = None #通过静态字段保存一个状态,然后一直访问这个静态字段
    def __init__(self,name):
        self.name = name

    @classmethod
    def get_instance(cls):
        #cls 类名
        if cls.instance:
            return cls.instance
        else:
            obj = cls("jack")
            cls.instance = obj
            return obj
obj1 = foo.get_instance()
obj2 = foo.get_instance()

异常捕获

1、异常处理——捕获所有异常

while True:
    num1 = input("num1:")
    num2 = input("numb2:")
    try: #try里面为正常的代码
        num1 = int(num1)
        num2 = int(num2)
        result = num1 + num2
    except Exception as ex: Exception为异常报错 ex为Exception的对象,ex里面封装了所有的错误信息。
        print(ex)

2、异常处理完整代码块

try: #正常代码块,先执行try
    pass 
except ValueError as ex: #再执行去特定异常信息
    print(ex) #str
except Exception as ex: #再捕获所有可能出现的异常
    print(ex)
else: # 否则通过
    pass
finally: #整个代码块不管是否有异常,最终都需要执行finally
    pass

3、主动抛出异常

try: #正常代码块,先执行try
    raise Exception(“主动抛出异常”) #self.message “主动抛出异常””
except ValueError as ex: #再执行去特定异常信息
    print(ex) #str
except Exception as ex: #再捕获所有可能出现的异常 #__str__.return self.message
    print(ex)
else: # 否则通过
    pass
finally: #整个代码块不管是否有异常,最终都需要执行finally
    pass

  

posted @ 2016-07-02 00:26  梁怀军  阅读(183)  评论(0编辑  收藏  举报