Python开发【第七篇】:面向对象二

字段

  1. class Foo:
  2.     #静态字段(保存在类中)
  3.     CC = 123
  4.  
  5.     def __init__(self):
  6.         #普通字段(保存在对象中)
  7.         self.name = 'alex'
  8.  
  9.     def show(self):
  10.         print(self.name)

静态字段的应用:

  1. class Province:
  2.  
  3.     def __init__(self,name):
  4.         self.name = name
  5.         country = "中国"
  6.  
  7. hn = Province('河南')
  8. hb = Province('河北')
  9. sd = Province('山东')
  10. hlj = Province('黑龙江')

节省内存空间:

  1. class Province:
  2.     country = "中国"
  3.  
  4.     def __init__(self,name):
  5.         self.name = name
  6.  
  7. hn = Province('河南')
  8. hb = Province('河北')
  9. sd = Province('山东')
  10. hlj = Province('黑龙江')

一般情况:自己访问自己的字段

规则:普通字段只能用对象访问,静态字段用类访问(可以使用对象访问)。

静态字段在代码加载时已经创建。

  1. print(hn.name)
  2. print(Province.country)

普通方法、静态方法、类方法

  1. class Province:
  2.     country = "中国"
  3.  
  4.     def __init__(self,name):
  5.         self.name = name
  6.  
  7.     #普通方法,由对象调用执行(方法属于类)
  8.     def show(self):
  9.         # print(self.name)
  10.         print("河北")
  11.  
  12.     #静态方法,由类调用执行(当方法内部不需要对象中封装的对象)
  13.     @staticmethod
  14.     def f1(arg1,arg2):
  15.         print(arg1,arg2)
  16.  
  17.     #类方法(静态方法的一种,至少一个参数,自动传递类名),由类调用执行
  18.     @classmethod
  19.     def f2(cls):
  20.         print(cls)
  21.  
  22. Province.f1(111,222)
  23. Province.f2()
  24.  
  25. obj = Province("河南")
  26. obj.show()
  27. 输出:
  28. 111 222
  29. <class '__main__.Province'>
  30. 河北

单例模式:类方法。

所有的方法属于类:

1、普通方法,至少一个self,对象执行。

2、静态方法,任意参数,类执行(可以对象执行)。

3、类方法,至少一个cls,类执行(可以对象执行)。

类成员属性

  1. class Pager:
  2.  
  3.     def __init__(self,all_count):
  4.         self.all_count = all_count
  5.  
  6.     def all_pager(self):
  7.         a1,a2 = divmod(self.all_count,10)
  8.         if a2 == 0:
  9.             return a1
  10.         else:
  11.             return a1 + 1
  12.  
  13. p = Pager(101)
  14. ret = p.all_pager() #方法
  15. print(ret)

 

  1. class Pager:
  2.  
  3.     def __init__(self,all_count):
  4.         self.all_count = all_count
  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.  
  14. p = Pager(101)
  15. ret = p.all_pager
  16. print(ret)

 

  1. class Pager:
  2.  
  3.     def __init__(self,all_count):
  4.         self.all_count = all_count
  5.  
  6.     #获取
  7.     @property
  8.     def all_pager(self):
  9.         a1,a2 = divmod(self.all_count,10)
  10.         if a2 == 0:
  11.             return a1
  12.         else:
  13.             return a1 + 1
  14.  
  15.     #设置
  16.     @all_pager.setter
  17.     def all_pager(self,value):
  18.         print(value)
  19.  
  20.     #删除
  21.     @all_pager.deleter
  22.     def all_pager(self):
  23.         print("del all_pager")
  24. p = Pager(101)
  25. ret = p.all_pager
  26. print(ret)
  27. p.all_pager = 111
  28. del p.all_pager
  29. 输出:
  30. 11
  31. 111
  32. del all_pager

属性:具有方法的写作形式,具有字段访问形式。

  1. class Pager:
  2.  
  3.     def __init__(self,all_count):
  4.         self.all_count = all_count
  5.  
  6.     def f1(self):
  7.         return 123
  8.  
  9.     def f2(self,value):
  10.         print(value)
  11.  
  12.     def f3(self):
  13.         print("del")
  14.  
  15.     foo = property(fget=f1,fset=f2,fdel=f3)
  16.  
  17. p = Pager(101)
  18. ret = p.foo
  19. print(ret)
  20. p.foo = "alex"
  21. del p.foo
  22. 输出:
  23. 123
  24. alex
  25. del

成员修饰符

  1. class Foo:
  2.  
  3.     #__cc私有静态字段
  4.     __cc = 123
  5.  
  6.     def __init__(self,name,age):
  7.         self.name = name
  8.         #__age私有普通字段
  9.         self.__age = age
  10.  
  11.     def f1(self):
  12.         print("f1:"+self.name)
  13.         print(self.__age)
  14.  
  15.     def f3(self):
  16.         print(Foo.__cc)
  17.  
  18.     @staticmethod
  19.     def f4():
  20.         print("staticmethod:",Foo.__cc)
  21.  
  22. class Bar(Foo):
  23.     def f2(self):
  24.         print(self.name)
  25.         #私有普通字段 不能访问
  26.         # print(self.__age)
  27.  
  28. obj = Foo('alex',19)
  29. print(obj.name)
  30. # print(obj.age) 不能外部调用
  31. # print(Foo.__cc) 不能外部调用
  32. obj.f1()
  33. obj.f3()
  34. Foo.f4()
  35.  
  36. obj1 = Bar("tom",20)
  37. obj1.f2()
  38. obj1.f1()

私有:只有类本身成员内部可以访问。

注意:特殊访问私有字段的方法(_类名__xxx)。

print(obj._Foo__age)

特殊成员

  1. class Foo:
  2.  
  3.     #构造方法
  4.     def __init__(self):
  5.         print("init")
  6.  
  7.     #析构方法
  8.     def __del__(self):
  9.         print("del")
  10.  
  11.     def __call__(*args,**kwargs):
  12.         print("call")
  13. p = Foo()
  14. #获取类名
  15. print(p.__class__)
  16. #执行call方法
  17. p()
  18. #执行call方法
  19. Foo()()
  20. 输出:
  21. init
  22. <class '__main__.Foo'>
  23. call
  24. init
  25. call
  26. del
  27. del

 

  1. class Foo:
  2.  
  3.     #构造方法
  4.     def __init__(self,name,age):
  5.         self.name = name
  6.         self.age = age
  7.  
  8.     #析构方法
  9.     def __del__(self):
  10.         pass
  11.  
  12.     def __call__(*args,**kwargs):
  13.         print("call")
  14.  
  15.     def __str__(self):
  16.         return "%s----%d" %(self.name,self.age)
  17.  
  18. obj = Foo("alex",34)
  19. print(obj)
  20. obj2 = Foo("eric",23)
  21. print(obj2)
  22. 输出:
  23. alex----34
  24. eric----23

 

  1. obj1 = Foo('alex',23)
  2. obj2 = Foo('eric',21)
  3. #获取对象中封装的数据
  4. ret = obj1.__dict__
  5. print(ret)
  6. 输出:
  7. {'age': 23, 'name': 'alex'}

 

  1. class Foo:
  2.  
  3.     #构造方法
  4.     def __init__(self,name,age):
  5.         self.name = name
  6.         self.age = age
  7.  
  8.     #析构方法
  9.     def __del__(self):
  10.         pass
  11.  
  12.     def __call__(*args,**kwargs):
  13.         print("call")
  14.  
  15.     def __str__(self):
  16.         return "%s----%d" %(self.name,self.age)
  17.  
  18.     def __getitem__(self,item):
  19.         print("getitem")
  20.  
  21.     def __setitem__(self, key, value):
  22.         print("setitem")
  23.  
  24.     def __delitem__(self, key):
  25.         print("delitem")
  26. obj = Foo('alex',18)
  27. #call方法
  28. obj()
  29. obj["abc"] = 111
  30. del obj['abc']
  31. 输出:
  32. call
  33. setitem
  34. delitem

 

  1. class Foo:
  2.  
  3.     #构造方法
  4.     def __init__(self,name,age):
  5.         self.name = name
  6.         self.age = age
  7.  
  8.     def __getitem__(self,item):
  9.         print(type(item))
  10.         if type(item) == str:
  11.             pass
  12.         else:
  13.             print(item.start)
  14.             print(item.stop)
  15.             print(item.step)
  16.  
  17.         print("getitem")
  18.  
  19.     def __setitem__(self, key, value):
  20.         print(type(key),type(value))
  21.         print("setitem")
  22.  
  23.     def __delitem__(self, key):
  24.         print(type(key))
  25.         print("delitem")
  26.  
  27. obj = Foo('alex',14)
  28. #getitem
  29. ret1 = obj[1:4:2]
  30. #getitem
  31. ret2 = obj['abc']
  32.  
  33. obj[1:3] = [11,22,33]
  34. del obj[1:5]
  35. 输出:
  36. <class 'slice'>
  37. 1
  38. 4
  39. 2
  40. getitem
  41. <class 'str'>
  42. getitem
  43. <class 'slice'> <class 'list'>
  44. setitem
  45. <class 'slice'>
  46. delitem

 

  1. class Foo:
  2.  
  3.     """
  4.     def __iter__(self):
  5.         print("iter")
  6.         return iter([11,22,333])
  7.     """
  8.     def __iter__(self):
  9.         yield 1
  10.         yield 2
  11.  
  12. obj = Foo()
  13. for item in obj:
  14.     print(item)
  15. 输出:
  16. """
  17. iter
  18. 11
  19. 22
  20. 333
  21. """
  22. 1
  23. 2

 

  1. class Bar:
  2.     pass
  3.  
  4. class Foo():
  5.     pass
  6. obj = Foo()
  7. #查看某个对象是不是由某个类创建
  8. ret = isinstance(obj,Foo)
  9. ret2 = isinstance(obj,Bar)
  10. print(ret)
  11. print(ret2)
  12. 输出:
  13. True
  14. False

isinstance和issubclass

  1. class Bar:
  2.     pass
  3.  
  4. class Foo(Bar):
  5.     pass
  6.  
  7.  
  8. obj = Foo()
  9. #查看某个对象是不是由某个类创建
  10. ret = isinstance(obj,Foo)
  11. ret2 = isinstance(obj,Bar) #obj类型和obj类型的父类
  12. print(ret)
  13. print(ret2)
  14.  
  15. #查看某个类是不是另一个类的子类
  16. ret3 = issubclass(Bar,Foo)
  17. ret4 = issubclass(Foo,Bar)
  18. print(ret3)
  19. print(ret4)
  20. 输出:
  21. True
  22. True
  23. False
  24. True

继承super

  1. class C2(C1):
  2.  
  3.     def f1(self):
  4.         #执行C1中的f1
  5.         super(C2,self).f1() #C1.f1(self)
  6.         print('c2.f1')
  7.  
  8. obj = C2()
  9. #默认执行C2中的f1
  10. obj.f1()
  11. 输出:
  12. c1.f1
  13. c2.f1

 

有序字典

  1. class MyDict(dict):
  2.  
  3.     def __init__(self):
  4.         self.li = []
  5.         super(MyDict,self).__init__()
  6.  
  7.     def __setitem__(self,key,value):
  8.         self.li.append(key)
  9.         super(MyDict,self).__setitem__(key,value)
  10.  
  11.     def __str__(self):
  12.         temp_list = []
  13.         for key in self.li:
  14.             value = self.get(key)
  15.             temp_list.append("'%s':%s"%(key,value))
  16.         temp_list = "{" + ",".join(temp_list) + "}"
  17.         return temp_list
  18.  
  19. obj = MyDict()
  20. obj['k1'] = 123
  21. obj['k2'] = 456
  22. print(obj)

单例模式

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

  1. class Foo:
  2.  
  3.     instance = None
  4.  
  5.     def __init__(self,name):
  6.         self.name = name
  7.  
  8.     @classmethod
  9.     def get_instance(cls):
  10.         #cls类名
  11.         if cls.instance:
  12.             print("已经创建对象")
  13.             return cls.instance
  14.         else:
  15.             #创建对象
  16.             obj = cls('alex')
  17.             print("新创建对象")
  18.             cls.instance = obj
  19.             return obj
  20.  
  21. obj = Foo.get_instance()
  22. obj1 = Foo.get_instance()
  23. print(id(obj),id(obj1))
  24. 输出:
  25. 新创建对象
  26. 已经创建对象
  27. 7225864 7225864

异常处理

  1. while True:
  2.     num1 = input("num1:")
  3.     num2 = input("num2:")
  4.     try:
  5.         num1 = int(num1)
  6.         num2 = int(num2)
  7.         result = num1 + num2
  8.     except Exception as ex: #捕获所有错误
  9.         print(ex)

 

  1. except ValueError as ve: #捕获ValueError
  2.     print(ve)
  3. except IndexError as ie: #捕获IndexError
  4.     print(ie)
  5. except Exception as ex: #捕获所有错误
  6.     print(ex)

 

  1. try:
  2.     pass
  3. except ValueError as ve:
  4.     print(ve)
  5. except Exception as ex:
  6.     print(ex)
  7. finally: #不管有无错误都执行finally
  8.     pass

 

  1. try:
  2.     raise ValueError('主动触发错误')
  3.     pass
  4. except ValueError as ve:
  5.     print("ValueError",ve)
  6. except Exception as ex:
  7.     print(ex)
  8. finally: #不管有无错误都执行finally
  9.     pass
  10. 输出:
  11. ValueError 主动触发错误

断言

  1. assert 1 == 1
  2. #报错
  3. assert 1 == 2

 

 

posted on 2017-02-08 12:31  yinshoucheng  阅读(376)  评论(0编辑  收藏  举报

导航