一、面向對象的概述
面向對象是一種描述業務問題、設計業務實體和實體之間關系的方法
二、類和對象
1、類和對象得區別:類是對客觀世界中事物得抽象,而對象是類實例化后的實體
例如:汽車模型就是一個類,制造出來的每輛汽車就是一個對象
2、類的定義:
(1)python使用class關鍵字定義一個類,類名的首字母一般要大寫:
例如:
class Student: #定義了一個Student類
(2)類的主體由一系列的屬性和方法組成
例如:
class Fruit: #定義一個類
def __init__(self): #類的構造函數,用於初始化類的內部狀態,為類的屬性設置默認值
self.name=name #定義name屬性
self.color=color #定義color屬性
def grow(self): #定義一個函數,為類的函數,稱為方法;它至少有一個參數self
print(‘Fruit grow’)
3、對象的創建:
創建對象的過程稱為實例化,當一個對象被創建后,包含3個方面的特性:對象的句柄、屬性和方法
對象的句柄:用於區分不同的對象
例如:
if __name__=="__main__" #當程序作為主程序運行
fruit=Fruit() #實例化:創建一個對象,創建了一個Fruit對象
fruit.grow() #對象調用grow()方法
4、類的屬性和方法
(1)類的屬性:一般分為公有屬性和私有屬性,默認情況下所有得屬性都是公有的,如果屬性的名字以兩個下划線開始,就表示為私有屬性,沒有下划線開始的表示公有屬性。 python的屬性分為實例屬性和靜態屬性,實例屬性是以self為前綴的屬性,如果構造函數中定義的屬性沒有使用self作為前綴聲明,則該變量只是普通的局部變量,類中其它方法定義的變量也只是局部變量,而非類的實例屬性。
例如:
class Fruit:
price=0 #定義一個類屬性
def __init__(self): #構造函數
self.color="red" #實例屬性,以self為前綴
zone="China" #局部變量,不以self為前綴
if __name__=="__main__":
print(Fruit.price) #使用類名調用類變量 0
apple=Fruit() #實例化apple
print(apple.color) #打印apple實例的顏色 red
Fruit.price=Fruit.price+10 #將類變量+10
print("apple's price:",+str(apple.price)) #打印apple實例的price 10
banana=Fruit() #實例化banana
print("banana's price:"+str(banana.price)) #打印banana實例的price 10
注意:python的類和對象都可以訪問類屬性;類的外部不能直接訪問私有屬性(屬性名以兩個下划線開始),當把上面的self.color=color改為self.__color="red",再次執行print(Fruit.__color)的時候就會報錯
(2)類的方法:類的方法也分為公有方法和私有方法,私有方法不能被模塊外的類或者方法調用,也不能被外部的類或函數調用。python利用staticmethon或@staticmethon 修飾器把普通的函數轉換為靜態方法
class Fruit:
price=0 #類變量
def __init__(self): #構造函數
self.__color="red" #定義一個私有屬性,類的外部不能直接訪問
def getColor(self): #類方法
print(self.__color) #打印出私有變量
@staticmenthod #使用修飾器靜態方法
def getPrice(): #定義一個類方法
print(Fruit.price) #打印類變量
def __getPrice(): #定義私有函數,不能被模塊外的類或者方法調用
Fruit.price=Fruit.price+10 #類變量+10
print(Fruit.price)
count=staticmenthod(__getPrice) #定義靜態方法
if __name__=="__main__":
apple=Fruit() #實例化apple
apple.getColor() #使用實例私有變量, red;因為創建了對象apple,所以靜態屬性price執行一次
Fruit.count() #使用列名直接調用靜態方法 10
banana=Fruit() #實例化 創建banana對象,所以靜態屬性第三次執行
Fruit.count() #實例調用靜態方法 20
Fruit.getPrice() # 20
(3)內部類的使用:在類的內部定義類
內部類中的方法可以使用兩種方法調用:
第一種:直接使用外部類調用內部類,生成內部類的實例,在調用內部類的方法
object_name = outclass_name.inclass_name()
object_name.method()
第二種:先對外部類進行實例化,然后再實例化內部類,最后調用內部類的方法
out_name = outclass_name()
in_name = out_name.inclass_name()
in_name.method()
(4)__init__方法:構造函數用於初始化類的內部狀態,為類的屬性設置默認值(是可選的)。如果不提供__init__方法,python將會給出一個默認的__init__方法
class Fruit:
def __init__(self, color):
self.__color = color
print( self.__color)
def getColor(self):
print( self.__color)
def setColor(self, color):
self.__color = color
print(self.__color)
if __name__ == '__main__':
color = 'red'
fruit = Fruit(color) #red
fruit.getColor() #red
fruit.setColor('blue') #blue
(5)__del__方法:構析函數用來釋放對象占用的資源(是可選的)。如果程序中不提供構析函數,python會在后台提供默認的構析函數;所以只有在需要的時候才會定義構析函數
————————————————
版權聲明:本文為CSDN博主「General_單刀」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_28284093/article/details/80092544