pythonのクラスclass定義とその初期化


クラスの定義、機能、属性の一般的なクラス名の頭文字の大文字

class Calculator:
#        
    name="jisuanqi" 
    price=28
    #          
    def add(self,x,y):
        print(self.name)#          -  
        result=x+y
        print(result)
    def subtract(self,x,y):
        print(x-y)
    def multiply(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)

calc=Calculator()
print(calc.name)#jisuanqi
print(calc.price)#28
print(calc.add(1,2))#3
print(calc.subtract(10,2))#8

出力:jisuanqi 28 jisuanqi 3 None 8 None
クラスの初期_init_

class Calculator:
    name="jisuanqi" #      
    price=28
    #   ,           
    def __init__(self,name,price,hight,width,weight):
        self.name=name
        self.price=price
        self.h=hight
        self.w=width
        self.weight=weight

    def add(self,x,y):
        print(self.name)
        result=x+y
        print(result)
    def subtract(self,x,y):
        print(x-y)
    def multiply(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)
#           
calc=Calculator('good calc',280,30,30,100)
print(calc.name)#jisuanqi
print(calc.weight)#100
print(calc.price)#280

出力結果:good calc 100 280