国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 面向對象之類class和對象基本用法示例

2020-02-15 21:27:55
字體:
來源:轉載
供稿:網友

本文實例講述了Python 面向對象之類class和對象基本用法。分享給大家供大家參考,具體如下:

類(class):定義一件事物的抽象特點,usually,類定義了事物的屬性和它可以做到的性為

對象(object):是類的實例。

1.基本點

class MyClass(object):  message = "hello,world"  def show(self):    print (self.message)

類名為MyClass 有一個成員變量:message,并賦予初值
類中定義了成員函數show(self),注意類中的成員函數必須帶有參數self
參數self是對象本身的引用,在成員函數中可以引用self參數獲得對象的信息

輸出結果:

inst = Myclass() # 實例化一個MyClass 的對象inst.show # 調用成員函數,無需傳入self參數hello,world

注: 通過在類名后面加小括號可以直接實例化類來獲得對象變量,使用對象變量可以訪問類的成員函數與成員變量。

2.構造函數

構造函數是一種特殊的類成員方法,主要用來創建對象初始化,python 中的類構造函數用__init__命名:

class MyClass(object):  message = 'Hello, Developer.'  def show(self):    print self.message  def __init__(self):    print "Constructor is called"inst = MyClass()inst.show()>>>

打印結果:

>>>Constructor is called>>>Hello, Developer.

注:構造函數不能有返回值,python 中不能定義多個構造函數,但可以通過為命名參數提供默認值的方式達到用多種方式構造對象的目的。

3.析構函數

是構造的反向函數,在銷毀或者釋放對象時調用他們。

python 中為類定義析構函數的方法在類定義中定義一個名為__del__的沒有返回值和參數的函數。

class MyClass(object):  message = 'Hello, Developer.'  def show(self):    print self.message  def __init__(self, name = "unset", color = "black"):    print "Constructor is called with params: ",name, " ", color  def __del__(self):    print "Destructor is called!"inst = MyClass()inst.show()inst2 = MyClass("David")inst2.show()del inst, inst2inst3 = MyClass("Lisa", "Yellow")inst3.show()del inst3>>>

打印結果:

Constructor is called with params:  unset   black
Hello, Developer.
Constructor is called with params:  David   black
Hello, Developer.
Destructor is called!
Destructor is called!
Constructor is called with params:  Lisa   Yellow
Hello, Developer.
Destructor is called!

4.實例成員變量

構造函數中定義self引用的變量,因此這樣的成員變量在python中叫做實例成員變量。

def __init__(self, name = "unset", color = "black"):  print "Constructor is called with params: ",name, " ", color  self.name = name  self.color = color            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 中卫市| 隆安县| 桐城市| 育儿| 久治县| 伽师县| 神农架林区| 大新县| 神池县| 磐安县| 高陵县| 鄂尔多斯市| 旬邑县| 遂川县| 奉节县| 广汉市| 罗江县| 贵德县| 疏勒县| 白银市| 陵水| 温宿县| 建瓯市| 班玛县| 公主岭市| 屯门区| 巴彦淖尔市| 历史| 唐山市| 合川市| 于田县| 长宁县| 寻乌县| 秭归县| 巫溪县| 本溪市| 大方县| 天柱县| 达孜县| 大石桥市| 胶州市|