python 2.03 面向对象
2017-01-31 12:04:12    72    0    0
admin

面向对象

注意
python 创建对象分为新版本的对象和旧版本的对象,旧版本的对象保留是为了向上兼容,一般情况下都可以直接使用新版本的对象。
创建新版本的对象的方式是在对象前几行写上

  1. __metaclass__ = type #以type 作为元类,具体解释比较复杂,以后再写

类的属性和方法

类的私有变量和方法

所有用__开头的变量或者方法都是私有变量和方法,不过还是可以通过其它的名字访问
事实上,只是把所有双下划线开头的名字前面加上了单下划线加类名而已

类变量/实例变量

类变量在类中公用,用 类名.变量名 调用
实例变量只属于这个实例,用 实例名.变量名 或者 self.变量名 调用

一些内置属性 (class 指类,object 指实例)

  1. class.__dict__ 类的属性
  2. class.__name__ 类名
  3. object.__dict__ 实例的属性
  4. class.__doc__ 类的介绍文档,在定义类的开头定义的
  5. class.__module__ 类定义所在的模块
  6. class.__bases__ 类的所有父类
  7. object.__class__ 实例的类
  8. object.__class__.__name__ 实例的类名

一些类内部的保留方法

  1. __init__ 初始化类的方法(构造方法)
  2. __del__ 类在被销毁时会调用的方法

一些方法

  1. hasattr(object, name) 返回布尔值,看一个对象中是否有某一个属性
  2. getattr(object, name[,default]) 获取对象的某个属性,如果不存在,返回默认值。如果获取的是方法,返回的则是该方法的内存地址,如果后面再加一对括号就是调用它。
  3. setattr(object, name, values) 修改对象的属性
  4. issubclass(child_class,bases_class) 返回布尔值,bases_class 是不是child_class 的父类
  5. isinstance(object, class) object 是不是class的实例对象或者class子类的实例对象
  6. super(自己的类名,self) 找到父类,只能用于新版本的类,可以在调用父类方法时使用

例子

code

  1. #!/usr/bin/python
  2. class team:
  3. 'read me' # 这一行会作为__doc__
  4. company_name="xx" #类变量
  5. def __init__(self,name,team_id="100"): #初始化方法
  6. self.team_name = name
  7. self.__team_id = team_id #__私有变量
  8. def set_name(self,name):
  9. self.team_name = name
  10. def get_name(self):
  11. return self.team_name
  12. def set_company_name(self,name):
  13. team.company_name = name
  14. def get_company_name(self):
  15. return team.company_name
  16. def __del__(self): #会在销毁类的时候被调用
  17. print "del:" + self.__class__.__name__ + ':' + self.team_name
  18. class employee(team): #team 的子类
  19. def __init__(self,team_name,name):
  20. self.team_name = team_name
  21. self.name = name
  22. def set_team_name(self,name):
  23. team.set_name(self,name) #调用父类方法的方式
  24. #super(employee,self).set_name(name) #如果是新版本的类的话可以这样写
  25. def get_team_name(self):
  26. return self.team_name
  27. sa = team("sa")
  28. network = team("network")
  29. print """
  30. Show the Class
  31. ==========================================================="""
  32. print "team.__dict__:",team.__dict__
  33. print "team.__doc__:",team.__doc__
  34. print "team.__module__:",team.__module__
  35. print "team.__bases__:",team.__bases__
  36. print "employee.__bases__:",employee.__bases__
  37. print "team.__name__:",team.__name__
  38. print "sa.__dict__:",sa.__dict__
  39. print "vars(sa)",vars(sa)
  40. print "sa.__class__:",sa.__class__
  41. print "sa.__class__.__name__:",sa.__class__.__name__
  42. print "sa.team_name:" + sa.team_name
  43. print "sa._team__team_id:" + sa._team__team_id #访问私有变量,还不够私有。。。。。嗯
  44. print 'hasattr(sa,"team_name"):',hasattr(sa,"team_name")
  45. print 'setattr(sa,"xx","xx"):',setattr(sa,"hahaha","wawawa")
  46. print 'after set attr:',sa.__dict__
  47. print 'getattr(sa,"team_name"):',getattr(sa,"get_name")
  48. print 'getattr(sa,"team_name")():',getattr(sa,"get_name")() #直接调用该方法
  49. print """
  50. using class function
  51. ==========================================================="""
  52. print "sa team name:"+sa.get_name()
  53. print "sa compant name:"+sa.get_company_name()
  54. sa.set_name("dba")
  55. print "sa set name to dba"
  56. print "sa team name:"+sa.get_name()
  57. print "compant name:"+network.get_company_name()
  58. sa.set_company_name("abcd")
  59. print "sa set company name to abcd"
  60. print "network team company name:"+network.get_company_name()
  61. print """
  62. SUB class:
  63. ==========================================================="""
  64. leo = employee("sa","leo")
  65. print "leo team name" + leo.get_team_name()
  66. print "leo set team name to abc"
  67. leo.set_team_name("abc")
  68. print "leo team name" + leo.get_team_name()
  69. print "employee is sub class of team :",issubclass(employee,team)
  70. print "sa is object from Class employee:",isinstance(sa,employee)
  71. print "sa is object from Class team:",isinstance(sa,team)
  72. print """
  73. Script end, auto delete the object:
  74. ==========================================================="""

运行结果

  1. [root@hadoop1 python]# ./oo.py
  2. Show the Class
  3. ===========================================================
  4. team.__dict__: {'set_name': <function set_name at 0x7f30518f25f0>, 'set_company_name': <function set_company_name at 0x7f30518f26e0>, '__del__': <function __del__ at 0x7f30518f27d0>, 'get_company_name': <function get_company_name at 0x7f30518f2758>, '__module__': '__main__', 'get_name': <function get_name at 0x7f30518f2668>, 'company_name': 'xx', '__doc__': 'read me', '__init__': <function __init__ at 0x7f30518f2578>}
  5. team.__doc__: read me
  6. team.__module__: __main__
  7. team.__bases__: ()
  8. employee.__bases__: (<class __main__.team at 0x7f30518e7890>,)
  9. team.__name__: team
  10. sa.__dict__: {'team_name': 'sa', '_team__team_id': '100'}
  11. vars(sa) {'team_name': 'sa', '_team__team_id': '100'}
  12. sa.__class__: __main__.team
  13. sa.__class__.__name__: team
  14. sa.team_name:sa
  15. sa._team__team_id:100
  16. hasattr(sa,"team_name"): True
  17. setattr(sa,"xx","xx"): None
  18. after set attr: {'team_name': 'sa', '_team__team_id': '100', 'hahaha': 'wawawa'}
  19. getattr(sa,"team_name"): <bound method team.get_name of <__main__.team instance at 0x7f30518faa70>>
  20. getattr(sa,"team_name")(): sa
  21. using class function
  22. ===========================================================
  23. sa team name:sa
  24. sa compant name:xx
  25. sa set name to dba
  26. sa team name:dba
  27. compant name:xx
  28. sa set company name to abcd
  29. network team company name:abcd
  30. SUB class:
  31. ===========================================================
  32. leo team namesa
  33. leo set team name to abc
  34. leo team nameabc
  35. employee is sub class of team : True
  36. sa is object from Class employee: False
  37. sa is object from Class team: True
  38. Script end, auto delete the object:
  39. ===========================================================
  40. del:team:network
  41. del:team:dba
  42. del:employee:abc

上一篇: python 2.01 异常处理

下一篇: python 2.04 迭代器和生成器

文档导航