python學習系列(三)類和對象

課程學習筆記參考https://coding.imooc.com/class/200.html(__bobby前輩所講)

1鴨子類型和多態,python中的鴨子類型,只需要有相同的方法,不需要繼承特定的類,鴨子類型和魔法函數構成了Python的協議。

2抽象基類 希望判定某個對象的類型,我們需要強制某個子類必須實現某些方法

#我們去檢查某個類是否有某種方法
class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __len__(self):
        return len(self.employee)


com = Company(["bobby1","bobby2"])
print(hasattr(com, "__len__"))

#我們在某些情況之下希望判定某個對象的類型
from collections.abc import Sized
isinstance(com, Sized)
print(isinstance(com, Sized))
>>>>>  

True
True

#如何去模擬一個抽象基類

import abc
from collections.abc import *


class CacheBase(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def get(self, key):
        pass

    @abc.abstractmethod
    def set(self, key, value):
        pass
class RedisCache(CacheBase):
    def set(self, key, value):
        pass

3isinstance type

type主要用於獲取未知變量的類型
isinstance主要用於判斷A類是否繼承於B類

4類屬性以及實例屬性

 

5類變量和對象變量

class A:
    aa = 1
    def __init__(self, x, y):
        self.x = x
        self.y = y

a = A(2,3)

A.aa = 11
a.aa = 100
print(a.x, a.y, a.aa)
print(A.aa)

b = A(3,5)
print(b.aa)

>>>>>>>>>>>>>>>

2 3 100
11
11

6靜態方法類方法以及對象方法

class Date:
    #構造函數
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def tomorrow(self):
        self.day += 1

    @staticmethod
    def parse_from_string(date_str):
        year, month, day = tuple(date_str.split("-"))
        return Date(int(year), int(month), int(day))

    @staticmethod
    def valid_str(date_str):
        year, month, day = tuple(date_str.split("-"))
        if int(year)>0 and (int(month) >0 and int(month)<=12) and (int(day) >0 and int(day)<=31):
            return True
        else:
            return False

    @classmethod
    def from_string(cls, date_str):
        year, month, day = tuple(date_str.split("-"))
        return cls(int(year), int(month), int(day))

    def __str__(self):
        return "{year}/{month}/{day}".format(year=self.year, month=self.month, day=self.day)

if __name__ == "__main__":
    new_day = Date(2018, 12, 31)
    new_day.tomorrow()
    print(new_day)

    #2018-12-31
    date_str = "2018-12-31"
    year, month, day = tuple(date_str.split("-"))
    new_day = Date(int(year), int(month), int(day))
    print (new_day)

    #用staticmethod完成初始化
    new_day = Date.parse_from_string(date_str)
    print (new_day)

    #用classmethod完成初始化
    new_day = Date.from_string(date_str)
    print(new_day)

    print(Date.valid_str("2018-12-32"))

7數據封裝和私有屬性

類中的變量前面加__,私有變量

8Python對象的自省機制

#自省是通過一定的機制查詢到對象的內部結構  __dict__可以獲取類和對象的屬性, dir列出對象中的所有屬性,只有屬性名稱沒有屬性值。

9super函數

10django rest franework的多繼承

11Python中的with語句

#上下文管理器協議
class Sample:
    def __enter__(self):
        print ("enter")
        #獲取資源
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        #釋放資源
        print ("exit")
    def do_something(self):
        print ("doing something")

with Sample() as sample:
    sample.do_something()

 

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