Python3基础之(十 九)class类 init功能

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/PoGeN1/article/details/84140267

一、init

__init__可以理解成初始化class的变量,取自英文中initial最初的意思.可以在运行时,给初始值赋值,

运行c=Calculator(‘bad calculator’,18,17,16,15),然后调出每个初始值的值。看如下代码。

class Calculator:
    name='good calculator'
    price=18
    def __init__(self,name,price,height,width,weight):   # 注意,这里的下划线是双下划线
        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):查看运行结果, 三个有默认值的属性,可以直接输出默认值,这些默认值可以在code中更改, 比如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
""""

def __init__(self,name,price,height,width,weight): 注意,这里的下划线是双下划线

猜你喜欢

转载自blog.csdn.net/PoGeN1/article/details/84140267