1.1 抽象基類(abc模塊)
python的抽象類的寫法,繼承抽象類的類必須要實(shí)現(xiàn)抽象方法,否則會(huì)報(bào)錯(cuò)
import abc
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):
print("setMethod")
def get(self, key):
print("getMethod")
redis_cache = RedisCache()
redis_cache.get('kv')
class A:
pass
class B(A):
pass
b = B()
print(isinstance(b, B)) # True
print(isinstance(b, A)) # True
print(type(A) is B) # False
1.2 類方法,靜態(tài)方法,實(shí)例方法
類方法相對靜態(tài)方法有一個(gè)好處, 類方法可以傳入一個(gè)類的實(shí)例代表這個(gè)類,而不用把類名寫死
class Date():
# 構(gòu)造函數(shù)
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
#實(shí)例方法
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))
@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__":
date_str="2018-01-19"
d = Date.from_string(date_str)
print(d) # 2018/1/19
1.3 類和實(shí)例方法查找順序
Python在多繼承時(shí)候查找順序采用c3算法
class D:
pass
class C(D):
pass
class B(D):
pass
class A(B,C):
pass
#順序:A,B,C,D
#__mro__,類的屬性查找順序
print(A.__mro__) # (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>,<class '__main__.D'>, <class 'object'>)
class D:
pass
class E:
pass
class C(E):
pass
class B(D):
pass
class A(B,C):
pass
print(A.__mro__) # (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.C'>, <class '__main__.E'>, <class 'object'>)
1.4 Python對象的自省機(jī)制
在計(jì)算機(jī)編程中小压,自省是指一種能力:檢查某些事物以確定它是什么贪嫂、它知道什么以及它能做什么。自省向程序員提供了極大的靈活性和控制力
class Person:
"""這是個(gè)人"""
name = "lala"
class Student(Person):
def __init__(self, scool_name):
self.scool_name = scool_name
self.lal = "緯度"
if __name__ == "__main__":
user = Student("慕課網(wǎng)")
# 通過__dict__查詢屬性
user.__dict__["school_aadd"] = "沈陽"
print(user.__dict__) # {'scool_name': '慕課網(wǎng)', 'lal': '緯度', 'school_aadd': '沈陽'}
print(Person.__dict__)
# {'__module__': '__main__', '__doc__': '這是個(gè)人', 'name': 'lala', '__dict__': <attribute '__dict__' of 'Person' objects>,
'__weakref__': <attribute '__weakref__' of 'Person' objects>}
print(Person.__doc__) # 這是個(gè)人
# dir也可以查看屬性综芥,比__dict__功能更強(qiáng)大
print(dir(user))
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'lal', 'name', 'school_aadd', 'scool_name']
1.5 super函數(shù)執(zhí)行順序
一問super是干什么的, 都知道它調(diào)用父類的方法, 可它的調(diào)用順序呢
# super執(zhí)行順序是怎樣的
class A:
def __init__(self):
print("A")
class B(A):
def __init__(self):
print("B")
super().__init__()
class C(A):
def __init__(self):
print("C")
super().__init__()
class D(B, C):
def __init__(self):
print("D")
super().__init__()
if __name__ == "__main__":
d = D()
1.6 with方法(上下文管理器)
with有點(diǎn)像裝飾器,使用起來很方便
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("lala")
with Sample() as sample:
sample.do_something()
# enter lala exit