「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=25
def thisMethod(self):
return 'hey this method worked’
exampleClass
exampleObject=exampleClass()
>>> exampleObject.eyes
'blue’
>>> exampleObject.age
25
>>> exampleObject.thisMethod()
'hey this method worked’
3.selfの利用方法
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="bacc"
var2="snausage"
>>> class child(parent):
var2="toast"
>>> pob=parent()
>>> cob=child()
>>> pob.var1
'bacc’
>>> pob.var2
'snausage’
>>> cob.var1
'bacc’
>>> cob.var2
'toast’