Python 객체용 샘플 코드

8794 단어 2017년 1월
#encoding:utf-8

'''example 1
class 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 '
====================
',v
for k in self.args: print str(k)+'\tvalue is '+str(self.args[k]) print self.args a = test(2014,a=123,b=321) a.kaka() a.deal_arg() ''' '''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__ ''' '''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.arg class 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 '*'*10 b.ParentsMethond() c.ParentsMethond() print '*'*10 c.Parenttest(3899) ''' '''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 ''' '''#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.__secretCount counter = JustCounter() counter.count() counter.count() counter.count() counter.count() counter.count() print counter.publicCount print counter.__secretCount # , print counter._JustCounter__secreCount '''

좋은 웹페이지 즐겨찾기