python学习笔记(5)

发布时间:2019-11-11编辑:脚本学堂
python学习笔记

函数,类,对象。
1、定义函数 def  

复制代码 代码如下:

def example(a,b,c):
 return a+b*c

>>> tuna=(5,7,3)
>>> example(*tuna)
26
>>> example(5,7,3)
26
>>> def example2(**this):
 print this

2、对象class  

复制代码 代码如下:
class exampleClass:
 eyes="blue"
 age=22
 def thisMethod(self):
  return 'hey this method worked'
exampleClass
<class __main__.exampleClass at 0x012283E8>
 exampleObject=exampleClass() //初始化对象
>>> exampleObject.eyes
'blue'
>>> exampleObject.age
22
>>> exampleObject.thisMethod()
'hey this method worked'

3、//其中的self指的是对象本身,例如下面的first,相当于java中的this
 

复制代码 代码如下:

 class className:
 def createName(self,name):
  self.name=name
 def displayName(self):
  return self.name
 def saying(self):
  print  "hello %s" % self.name

>>> first=className()
>>> second = className()
>>> first.createName('bucky')
>>> second.createName('tondy')
>>> first.displayName()
'bucky'
>>> first.saying()
hello bucky

4、父类,子类  

复制代码 代码如下:

class parentClass:
 var1="i am var1"
 var2="i am var2"
 
>>> class childClass(parentClass):
 pass

>>> parentObject=parentClass()
>>> parentObject.var1
'i am var1'
>>> childObject=childClass()
>>> childObject.var1
'i am var1'
>>> childObject.var2
'i am var2'

5、覆写父类  

复制代码 代码如下:
class parent:
 var1="bacon"
 var2="snausage"
 
>>> class child(parent):
 var2="toast"
 
>>> pob=parent()
>>> cob=child()
>>> pob.var1
'bacon'
>>> pob.var2
'snausage'
>>> cob.var1
'bacon'
>>> cob.var2
'toast'