Python面向对象程序设计示例小结

  

本文实例讲述了Python面向对象程序设计。分享给大家供大家参考,具体如下:

  

<强>示例1:

        utf - 8编码:   “示例1   类测试:   def __init__(自我,,* *参数):   自我。年=一年   自我。args=参数   def卡卡(自我):   如果isinstance (self.year, str):   打印输入\ '年代是一个字符串!错误的   elif isinstance (self.year, int):=self.year % 4   打印一个   其他:   打印的错误!   def deal_arg(自我):   #在self.args v:   #打印' \ n====================\ n ', v   在self.args k:   打印str (k) + ' \ tvalue“+ str (self.args [k])   打印self.args=123=测试(2014,b=321)   a.kaka ()   a.deal_arg ()      之前      

运行结果:

  
  2


  a 值为123
  b 值为321
  {' a ': 123, ' b ': 321}

     

<强>示例2:

        utf - 8编码:   “2”   类测试:   “这是一个测试的基类的   def __init__(自我、测试):   自我。测试=测试   “这是一个测试的基类的   打印“test.__doc__:’, test.__doc__   打印“test.__name__:’, test.__name__   打印“test.__module__:’, test.__main__   打印“test.__bases__:’, test.__bases__   打印“test.__dict__:’, test.__dict__      之前      

<强>示例3:

        “示例3类继承和方法部分重写”   父类:   def __init__(自我):   打印”这是一个父类的   def ParentsMethond(自我):   打印”这是一个父类方法”   def父(自我,arg):   自我。arg='这是一个测试!”   打印的父类的自我变量:% s的% self.arg   的父母。arg=参数   打印的父类的变量:% s的% parent.arg   类儿童(父母):   docstring儿童“”“”   def __init__(自我):   打印”这是一个子类的   def ChildMethod(自我):   打印“调用子类方法孩子方法”   def ParentsMethond(自我):   打印的父类方法重写! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !”   b=父()   孩子c=()   c.ChildMethod ()   打印* * 10   b.ParentsMethond ()   c.ParentsMethond ()   打印* * 10   c.Parenttest (3899)      之前      

运行结果:

  
  

这是一个父类
  这是一个子类
  调用子类方法孩子方法
  * * * * * * * * * *
  这是一个父类方法
  父类方法重写! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
  * * * * * * * * * *
  父类的自我变量:这is 一个测试!
  父类的变量:3899

     

<强>示例4:

        “示例4”操作符重载   类测试:   def __init__(自我,a, b):   自我。一个=自我。b=b   def __str__(自我):   返回向量(% d % d)的% (self.a self.b)   def __add__(自我,其他):   回归测试(self.a + other.a self.b + other.b)   v1=测试(21、22)   v2=测试(2、3)   打印v1 + v2      之前      

运行结果:

  
  

矢量(23日25)

     

<强>示例5:

        “# 5私有类”   类JustCounter(对象):   JustCounter docstring“”“”“”   __secretCount=0 #私有变量   publicCount=0 #公开变量   def计数(自我):   自我。__secretCount +=1   自我。publicCount +=1   打印self.__secretCount   counter=JustCounter ()   counter.count ()   counter.count ()   counter.count ()   counter.count ()   counter.count ()   打印counter.publicCount   打印计数器。__secretCount #报错,实例不能访问私有变量   打印counter._JustCounter__secreCount      之前      

感兴趣的朋友可以测试上述代码运行效果。

  

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》,《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》

  

希望本文所述对大家Python程序设计有所帮助。

Python面向对象程序设计示例小结