ソースコード
#coding:utf-8
#class 2025/2/11
#classの定義:classはあるオブジェクトのテンプレートに相当する
#クラスの名前は第1文字大文字で、残りは小文字とします。
#例1
class Car:
def __init__(self,brand,color,type,price,picture): #initialize 初期化
#self means created instance itself automatically do not need pass anything to self
#attributes 属性,特徴の定義
self.brand = brand
self.color = color
self.type = type
self.price = price
self.picture = picture
#methods 方法の定義
def info(self):
print(f"The car of {self.brand} is {self.color}, type is {self.type}.")
print(f"価格={self.price} 写真={self.picture}")
#instance,object オブジェクトの実例
Tesla = Car("Tesla","Black","Model Y",2000000,"./images/aso.jpg")
Tesla.info()
#例2
class Person:
#初期化
def __init__(self,f_name,l_name):
#attributes 属性,特徴の定義
self.firstname = f_name
self.lastname = l_name
#method
def print_name_eng(self):
print(self.firstname,self.lastname)
#method
def print_name_jp(self):
print(self.lastname,self.firstname)
#instance,object
x = Person("Nhung","桜原")
x.print_name_jp()
y = Person("John","Smith")
y.print_name_eng()
#例3
class Rectangle:
#初期化
def __init__(self,length,width):
#attributes 特徴量、属性
self.rect_length = length
self.rect_width = width
#methods
def print_area(self):
print(f"面積 = {self.rect_length * self.rect_width}")
#instances
for i in range(3):
x = int(input("長方形の縦幅: "))
y = int(input("長方形の横幅: "))
shape = Rectangle(x,y)
shape.print_area()