本文實例講述了Python面向對象程序設計。分享給大家供大家參考,具體如下:
示例1:
#encoding:utf-8'''example 1class test: def __init__(self,year,**arg): self.year = year self.args = arg def kaka(self): if isinstance(self.year,str): print 'input/'s year is a string! Error' elif isinstance(self.year,int): a = self.year%4 print a else: print 'Error!' def deal_arg(self): # for v in self.args: # print '/n====================/n',v for k in self.args: print str(k)+'/tvalue is '+str(self.args[k]) print self.argsa = test(2014,a=123,b=321)a.kaka()a.deal_arg()
運行結果:
2
a value is 123
b value is 321
{'a': 123, 'b': 321}
示例2:
#encoding:utf-8'''example 2'''class test: '這是一個測試的基類' def __init__(self,test): self.test = test '這是一個測試的基類'print 'test.__doc__:',test.__doc__print 'test.__name__:',test.__name__print 'test.__module__:',test.__main__print 'test.__bases__:',test.__bases__print 'test.__dict__:',test.__dict__
示例3:
'''example 3 Class inheritance and method partial rewriting'''class parent: def __init__(self): print '這是一個父類' def ParentsMethond(self): print '這是一個父類方法' def Parenttest(self,arg): self.arg = 'This is a test!' print '父類的self變量: %s' %self.arg parent.arg = arg print '父類的變量: %s' %parent.argclass child(parent): """docstring for child""" def __init__(self): print '這是一個子類' def ChildMethod(self): print '調用子類方法 child method' def ParentsMethond(self): print '父類方法重寫!!!!!!!!!!!!!!!!!!!!'b= parent()c = child()c.ChildMethod()print '*'*10b.ParentsMethond()c.ParentsMethond()print '*'*10c.Parenttest(3899)
運行結果:
這是一個父類
這是一個子類
調用子類方法 child method
**********
這是一個父類方法
父類方法重寫!!!!!!!!!!!!!!!!!!!!
**********
父類的self變量: This is a test!
父類的變量: 3899
示例4:
'''example 4 Operator overloading'''class test: def __init__(self,a,b): self.a = a self.b = b def __str__(self): return 'Vector (%d,%d)' % (self.a,self.b) def __add__(self,other): return test(self.a+other.a,self.b+other.b)v1 = test(21,22)v2 = test(2,3)print v1 + v2
運行結果:
Vector (23,25)
示例5:
'''#example 5 private class'''class JustCounter(object): """docstring for JustCounter""" __secretCount = 0 #私有變量 publicCount = 0 #公開變量 def count(self): self.__secretCount +=1 self.publicCount +=1 print self.__secretCountcounter = JustCounter()counter.count()counter.count()counter.count()counter.count()counter.count()print counter.publicCountprint counter.__secretCount #報錯,實例不能訪問私有變量print counter._JustCounter__secreCount
新聞熱點
疑難解答