DAY 22
0
Software Development

## [Day26] init and self

``````class abc:
def __init__(self,var1,var2...):
self.var_1=var1
self.var_2=var2
self.xxxx=xxxx
....
K=self.var_1+self.var_2
return K
def disply(self):
peint(sekf.K)
return

``````
• `self`
就是自己、本身。指的是在創建class的物件或者instance時，self就是指這個被創建的物件本身，你也可以寫成其他的東西，比如寫成somethong也是可以的，這樣的話就要改成`somethong.var_1`。當然，`self.var_1=var1`是指把self中var_1這個屬性指定var1這個值，`self.function()`是指當
• `__init__`
被用來"初始化"新物件(initialization of a new instance)的函數

``````class abc:
def __init__(self,var1=0,var2=0): #可以先給參數預設值
self.var_1=var1
self.var_2=var2

K=self.var_1+self.var_2
return K
def disply(self):
return

k=abc(10,12)
k.disply() #output:22
``````

``````class Rectangle:
def __init__(self,l=0,b=0,cost=0): #可以先給參數預設值
self.length=l
self.unit_cost=cost
def get_perimeter(self):
return 2 * (self.length + self.breadth)
def get_area(self):
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 200 cm, length = 400 cm, 1 cm^2 cost=200
r = Rectangle(400,200,200)
#r.length = 400  r.breadth = 200  r.unit_cost = 200
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: %s " %(r.calculate_cost()))
#Area of Rectangle: 80000 cm^2
#Cost of rectangular field:  16000000
``````