class_Y

3619 days ago by takepwave

class Y: """ Mathematical function for the vertical motion of a ball. Methods: constractor(v0): set initial velocity v0. value(t): compute the height as function of t. formula(): print out the formula for the height. Attributes: v0: the initial velocity of the ball (time 0). g: acceleration of gravity (fixed). Usage: >>> y = Y(3) >>> position1 = y.valu(0.1) >>> position2 = y.value(0.3) >>> print y.formula() v0*t - 0.5+g*t**2; v0=3 """ def __init__(self, v0): self.v0 = v0 self.g =9.81 def value(self, t): return self.v0*t - 0.5*self.g*t**2 def formula(self): return 'v0*t - 0.5*t**2; v0=%g' % self.v0 
       
y = Y(5) t = 0.2 v = y.value(t) print 'y(t=%g; v0=%g) = %g' % (t, y.v0, v) print y.formula() 
       
y(t=0.2; v0=5) = 0.8038
v0*t - 0.5*t**2; v0=5
y(t=0.2; v0=5) = 0.8038
v0*t - 0.5*t**2; v0=5

実験の結論: メッソド formula を class の中で変更した後、評価しないと変更は反映されない。

def formula(self): return 'test: v0*t - 0.5*t**2; v0=%g' % self.v0 
       
y = Y(5) t = 0.2 v = y.value(t) print 'y(t=%g; v0=%g) = %g' % (t, y.v0, v) print y.formula() 
       
y(t=0.2; v0=5) = 0.8038
v0*t - 0.5*t**2; v0=5
y(t=0.2; v0=5) = 0.8038
v0*t - 0.5*t**2; v0=5

実験の結論: メッソド formula を class の中で変更した後、評価しないと変更は反映されない。

class Y: """ Mathematical function for the vertical motion of a ball. Methods: constractor(v0): set initial velocity v0. value(t): compute the height as function of t. formula(): print out the formula for the height. Attributes: v0: the initial velocity of the ball (time 0). g: acceleration of gravity (fixed). Usage: >>> y = Y(3) >>> position1 = y.valu(0.1) >>> position2 = y.value(0.3) >>> print y.formula() v0*t - 0.5+g*t**2; v0=3 """ def __init__(self, v0): self.v0 = v0 self.g =9.81 def value(self, t): return self.v0*t - 0.5*self.g*t**2 def formula(self): return 'class: v0*t - 0.5*t**2; v0=%g' % self.v0 
       
y = Y(5) t = 0.2 v = y.value(t) print 'y(t=%g; v0=%g) = %g' % (t, y.v0, v) print y.formula() 
       
y(t=0.2; v0=5) = 0.8038
class: v0*t - 0.5*t**2; v0=5
y(t=0.2; v0=5) = 0.8038
class: v0*t - 0.5*t**2; v0=5

クラスは、不要

Y. Satoさま、クラスにこだわる必要はなく、クラスのインスタンス変数(self.変数名)はノートブック内のグローバル変数(単に変数に値をセットしたもの) とユーザ定義関数(defで定義した関数)で少しずつ動作を確認しながら、動かしていくのがよいと思います。

上記のclass Yをノートブック風に書くと以下の様になります。

# Mathematical function for the vertical motion of a ball. # # v0: the initial velocity of the ball (time 0). # g: acceleration of gravity (fixed). v0 = 5 g = 9.81 
       
# value(t): compute the height as function of t. def value(t): return v0*t - 0.5*g*t**2 
       
# formula(): print out the formula for the height. def formula(): return 'v0*t - 0.5*t**2; v0=%g' % v0 
       
t = 0.2 v = value(t) print 'y(t=%g; v0=%g) = %g' % (t, v0, v) print formula() 
       
y(t=0.2; v0=5) = 0.8038
v0*t - 0.5*t**2; v0=5
y(t=0.2; v0=5) = 0.8038
v0*t - 0.5*t**2; v0=5