class 類別 init 功能

__init__,取自英文中initialize,用來初始化class的變數。在執行此類別時,給予變數初始值。

以下執行c=Calculator('bad calculator',18,17,16,15),然後印出每個初始值的值 :

class Calculator:
    name = 'good calculator'
    price = 18
    def __init__(self, name, price, height, width, weight):
        # 注意, __init__ 是雙底線
        self.name = name
        self.price = price
        self.h = height
        self.wi = width
        self.we = weight

"""
> c = Calculator('bad calculator', 18, 17, 16, 15)
> c.name
'bad calculator'
> c.price
18
> c.h
17
>c.wi
16
> c.we
15
"""

變數的預設值,直接在def裡輸入即可,如下:

def __init__(self,name,price,height=10,width=14,weight=16):查看執行結果,三個有預設值的屬性 ( height = 10, width=14, weight=16 ),可以直接輸出預設值,這些預設值可以更改,比如輸入c.wi=17,再印出c.wi就會把wi屬性值更改為17。

class Calculator:
    name = 'good calculator'
    price = 18
    def __init__(self, name, price, hight=10, width = 14, weight = 16):
        #后面三个属性设置默认值,查看运行
        self.name = name
        self.price = price
        self.h = hight
        self.wi = width
        self.we =weight

""""
> c=Calculator('bad calculator',18)
> c.h
10
> c.wi
14
> c.we
16
> c.we=17
> c.we
17
""""

Reference

[0] https://morvanzhou.github.io/tutorials/python-basic/basic/09-2-class-init/

results matching ""

    No results matching ""