python知識撿拾---類方法篇

python的屬性分爲實例屬性和靜態屬性

實例屬性是以self作爲前綴的屬性
instance實例化對象
內置屬性的使用:

#-*-encoding:utf-8-*-
class Fruit:
    price = 0
    def __init__(self):
        self.__color="blue" #私有屬性

class Apple(Fruit):        #Apple繼承了Fruit
    pass

if __name__=="__main__":
    fruit=Fruit()
    apple=Apple()
    print Apple.__bases__   #輸出基類組成的元組
    print apple.__dict__    #輸出屬性組成的字典 結果爲:{'_Fruit__color': 'blue'}
    print apple.__module__  #輸出類所在的模塊名 結果爲:__main__
print apple.__doc__         #輸出doc文檔

類的方法:
python使用函數staticmethod()或"@ staticmethod"指令的方式把普通的函數轉換爲靜態方法,python的靜態方法並沒有和類的實例進行名稱綁定,python的靜態方法相當於全局函數

類方法可以使用classmethod()或"@ classmethod"指令定義
類方法的使用和靜態方法十分相似,如果某個方法需要被其他實例共享,同時又需要使用當前實例的屬性,則將其定義爲類方法

內部類的使用:
在某個內部類定義的類稱之爲內部類,內部類中的方法可以使用兩種方法調用:
一種是直接使用外部類調用內部類,生成內部類的實例,再調用內部類的方法,調用格式如下:

object_name = outclass_name.inclass_name()
object_name.method()

第二種方法是先對外部類進行實例化,然後在實例化內部類,最後再調用內部類方法,調用格式如下:

out_name = outclass_name()
in_name = out_name.inclass_name()
in_name.method()

垃圾回收機制:
python提供了gc模塊釋放不再使用的對象,垃圾回收的機制有許多種算法
python採用的是引用計數的方式。當某個對象在其作用域內不再被其他對象引用時,python就會自動清除該對象。垃圾回收機制很好地避免了內存泄漏的發生。函數collect()可以一次性收集所有待處理的對象
實例:

#-*-encoding:utf-8-*-
import gc
class Fruit:
    def __init__(self,name,color):
        self.__name = name
        self.__color = color

    def getColor(self):
        return self.__color

    def setColor(self,color):
        self.__color=color

    def getName(self):
        return self.__name

    def setName(self,name):
        self.__name = name

class FruitShop:          #水果店類
    def __init__(self):
        self.fruits = []   #定義了屬性fruits,fruits是1個列表,用於存放水果店中的水果

    def addFruit(self,fruit):   #添加水果,把對象fruit添加到fruits列表中
        fruit.parent = self     #把Fruti類關聯到FruitShop類,設置fruit對象的parent屬性爲self.即把FruitShop實例化對象的引用關聯到添加的fruit對象上
        self.fruits.append(fruit)

if __name__=="__main__":
    shop = FruitShop()
    shop.addFruit(Fruit("apple","red"))   #向shop對象中添加兩個fruit對象
    shop.addFruit(Fruit("banana","yellow"))
    print gc.get_referrers(shop)  #調用函數get_referrers()列出shop對象關聯的所有對象
    del shop            #刪除shop對象,但是shop對象關聯的其他對象並沒有釋放
    print gc.collect()   #顯示調用垃圾回收機制,調用collect()釋放shop對象關聯的其他對象,collect()返回結果表示釋放的對象個數。輸出結果爲7

類的內置方法:

內置方法 說明
init(self,…) 初始化對象,在創建新對象時調用
del(self) 釋放對象,在對象被刪除之前調用
new(cls,*args,**kwd) 實例的生成操作
str(self) 在使用print語句時被調用
getitem(self,key) 獲取序列的索引key對應的值,等價於seq[key]
len(self) 在調用內聯函數len()時被調用
cmp(src,dst) 比較兩個對象src和dst
getattr(s,name) 獲取屬性的值
setattr(s,name,val) 設置屬性的值
delattr(s,name) 刪除name屬性
getattribute() getattribute()的功能與__getattr__()類似
gt(self,other) 判斷self對象是否大於other對象
lt(self,other) 判斷self對象是否小於other對象
ge(self,other) 判斷self對象是否大於或等於other對象
le(self,other) 判斷self對象是否小於或等於other對象
eq(self,other) 判斷self對象是否等於other對象
call(self,*args) 把實例對象作爲函數調用

new():
它會在__init__()之前被調用,用於生成實例對象。利用這個方法和類屬性的特性可以實現設計模式中的單例模式。
單例模式設計的類只能實例化1個對象

#-*-encoding:utf-8-*-
class Singleton(object):
    __instance = None    #定義私有的類屬性,__instance的值是第一次創建的實例,以後的實例化操作都將共享這個屬性。因此達到了創建唯一實例的目的

    def __init__(self):
        pass

    def __new__(cls, *args, **kwd):#重新實現方法__new__()
        if Singleton.__instance is None: #判斷當前的實例是否爲"None"如果爲"None"則調用父類object的__new__()方法,生成一個唯一實例
            Singleton.__instance=object.__new__(cls,*args,**kwd)
        return Singleton.__instance  #返回唯一實例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章