
【pythonの基礎#5】クラス
記事の目的
pythonの基礎である、for文とif文と自作関数について実装していきます。ここにある全てのコードは、コピペで再現することが可能です。
目次
1 クラスの初期設定

# In[1]
class Tatsuki1:
def __init__(self):
self.weight = 60
self.height = 170
# In[2]
object1 = Tatsuki1()
# In[3]
object1.weight, object1.height
2 クラスの関数

# In[4] class Tatsuki2: def __init__(self): self.weight = 60 self.height = 170 def eat(self,x): self.weight = self.weight + x def milk(self,x): self.height = self.height + x def diet(self,x): self.weight = self.weight - x # In[5] object2 = Tatsuki2() object2.weight, object2.height # In[6] object2.eat(10) object2.weight, object2.height # In[7] object2.milk(20) object2.weight, object2.height # In[8] object2.diet(10) object2.weight, object2.height
3 クラスの継承

# In[9]
class Man:
def eat(self,x):
self.weight = self.weight + x
def milk(self,x):
self.height = self.height + x
def diet(self,x):
self.weight = self.weight - x
class Tatsuki(Man):
def __init__(self):
self.weight = 60
self.height = 170
class Akira(Man):
def __init__(self):
self.weight = 70
self.height = 180
# In[10]
object3 = Tatsuki()
object3.weight, object3.height
# In[11]
object3.eat(10)
object3.weight, object3.height
# In[12]
object4 = Akira()
object4.weight, object4.height
# In[13]
object4.milk(10)
object4.weight, object4.height