本文實例講述了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
新聞熱點
疑難解答