Python類和執行個體,Python類執行個體

來源:互聯網
上載者:User

Python類和執行個體,Python類執行個體

物件導向最重要的概念就是類(Class)和執行個體(Instance),必須牢記類是抽象的模板,比如Student類,而執行個體是根據類建立出來的一個個具體的“對象”,每個對象都擁有相同的方法,但各自的資料可能不同。雖然本質和C#或者JAVA相同但是在寫法上還是有一定的差距的

仍以Student類為例,在Python中,定義類是通過class關鍵字,後面跟參數。

class Student(object):    pass

一般沒有繼承話就用object代替,如果Python想用相關的屬性,就要用到self關鍵字,這有點像C#裡面的建構函式,只是Python裡面不需要聲明相關屬性

>>> class Student(object):...         def __init__(self,name,age):...                    self.name=name...                     self.age=age>>>>>>a=Student('張三',24)>>>a.name張三>>>a.age24

同時不僅僅可以帶上自己的屬性,同時也能寫方法

>>> class Dog(object):...            def Eat(self):...                 print('i am dog')>>>a=Dog()>>>a.Eat()i am dog

同時也可以返回傳回值與函數沒有啥區別

>>>class Dog(object):...         def Myname(self):...               return 'my name is dog'...>>>b=Dog()>>>b.Myname()my name is dog

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.