5_Python OOP

1. 實例屬性和類屬性

       (1) 實例屬性在構造函數__init__中定義,定義時以self做爲前綴,只能經過實例名訪問python

       (2) 類屬性在類中方法以外單獨定義,還能夠在程序中經過類名增長,建議經過類名直接訪問。app

class Product:                          ##建議首字母大寫
    price = 100                         ##類屬性
    def __init__(self,c):
        self.color = c                  ##實例屬性

##主程序
Product1 = Product("red")
Product2 = Product("yellow")

Product.price = 120                     ##修改類屬性值
Product.name = "shoes"                  ##增長類屬性

Product1.color = "black"                ##修改實例屬性

       (3) 私有屬性以__開頭,不然是公有屬性。私有屬性在類外不能直接訪問。而是經過特殊方式訪問私有屬性:函數

class Food:
    def __init__(self):
        self.__color = 'red'            ##私有屬性定義格式
        self.price = 0

##主程序
>>>apple = Food()
>>>apple.(_)Food__color = "blue"        ##私有屬性修改格式
>>>print(apple._Food__color)            ##私有屬性訪問格式

blue


2. 類的方法

class Fruit:
    price = 0                           ##類屬性
    
    def __init__(self):                 
        self.__color = 'red'            ##私有屬性
    
    def __outputColor(self):            ##私有方法
        print(self.__color)
        
    def output(self):                   ##公有方法
        self.__outputColor()
        
    @staticmethod                       ##靜態方法
    def getprice():                     
        return Fruit.frice
    
    @classmethod                        ##類方法
    def fget(cls):
        print(cls)


3. 構造函數和析構函數

def __init__(self,first = '',last = '',id = 0):
    self.firstname = first
    self.lastname = last
    self.idint = id

def __del__(self):
    print("self was dead")


4. 經常使用的運算符重載

方法 重載 調用
__add__ + x+y
__or__ | x|y
__repr__ 打印 repr(x)
__str__ 轉換 str(x)
__call__ 函數調用 x(*args,**key)
__getattr__ 點號運算 x.undefine
__setattr__ 屬性賦值 x.any=value
__delattr__ 屬性刪除 del x.any
__getattribute__ 屬性獲取 x.any
__getitem__ [] x[key]
__setitem__ 索引賦值 x[key]=value
__delitem__ 索引刪除 del x[key]
__len__ 長度 len(x)
__bool__ 布爾測試 bool(x)
__lt__,__gt__ 小於,大於
__le__,__ge__ 小於等於,大於等於
__eq__,__ne__ 等於,不等於
__contain__ in item in x
__iter__,__next__ 迭代 I=iter(x),next(x)


5. 繼承

        與C++繼承實現相似測試

class sub(super):
    def __init__(self):
相關文章
相關標籤/搜索