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

时间:2023-03-09 09:08:37
Python开发【第七篇】:面向对象二

字段

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

静态字段的应用:

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

节省内存空间:

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

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

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

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

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

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

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

单例模式:类方法。

所有的方法属于类:

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

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

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

类成员属性

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

 

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

 

  1. class Pager:
  2.     def __init__(self,all_count):
  3.         self.all_count = all_count
  4.     #获取
  5.     @property
  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.     @all_pager.setter
  14.     def all_pager(self,value):
  15.         print(value)
  16.     #删除
  17.     @all_pager.deleter
  18.     def all_pager(self):
  19.         print("del all_pager")
  20. p = Pager(101)
  21. ret = p.all_pager
  22. print(ret)
  23. p.all_pager = 111
  24. del p.all_pager
  25. 输出:
  26. 11
  27. 111
  28. del all_pager

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

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

成员修饰符

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

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

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

print(obj._Foo__age)

特殊成员

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

 

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

 

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

 

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

 

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

isinstance和issubclass

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

继承super

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

 

有序字典

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

单例模式

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

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