Python--__init__方法

來源:互聯網
上載者:User

標籤:print   顯示   sleep   color   div   style   school   tin   col   

一、說明

__init__方法用來為對象定製自己專屬的特徵

二、範例程式碼如下

 1 class LuffyStudent(): 2     school = ‘luffycity‘ 3  4     def __init__(self, name, sex, age): 5         self.Name = name 6         self.Sex = sex 7         self.Age = age 8  9     def learn(self):10         print(‘is learning‘)11 12     def eat(self):13         print(‘is eating‘)14 15     def sleep(self):16         print(‘is sleeping‘)

產生對象代碼如下:

1 stu1 = LuffyStudent(‘王一丫‘, ‘女‘, 18)  # 相當於LuffyStudent.__init__(stu1,‘王一丫‘,‘女‘,18)

加上__init__方法後,類樣本化的步驟如下:

1、先產生一個Null 物件,stu1

2、LuffyStudent.__init__(stu1,‘王一丫‘,‘女‘,18)

查看stu1的名稱空間:

1 print(stu1.__dict__)

結果如下:

{‘Name‘: ‘王一丫‘, ‘Sex‘: ‘女‘, ‘Age‘: 18}

這就顯示為對象定製了自己專屬的特徵

 

查看對象的資料屬性,代碼如下:

1 print(stu1.Name)2 print(stu1.Sex)3 print(stu1.Age)

結果如下:

王一丫

18

更改對象的資料屬性,代碼如下:

1 stu1.Name = ‘李一丫‘2 print(stu1.Name)

結果如下:

李一丫

刪除對象的資料屬性,代碼如下:

1 del stu1.Name2 print(stu1.__dict__)

結果如下:

{‘Sex‘: ‘女‘, ‘Age‘: 18}

增加對象的資料屬性,代碼如下:

1 stu1.class_name = ‘python開發‘2 print(stu1.__dict__)

結果如下:

{‘Sex‘: ‘女‘, ‘Age‘: 18, ‘class_name‘: ‘python開發‘}

 

Python--__init__方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.