前言:類是什么?類是從一堆對象中抽取出來的相同的屬性和方法的集合,換句話說類也是object。
抽象類:
概念: 從一堆類中抽取出來的相同的方法的集合,規定了兼容接口
特點: 1. 只能被繼承,不能實例化
2. 子類必須繼承抽象類中定義的對象方法、綁定類方法、類方法、靜態方法
3. 可以添加成員屬性
4. 抽象類中可以定義抽象方法,也可定義正常方法
# @Time : 2022/2/22 23:48
# @Author : Bella
# -*- coding: utf-8 -*-
import abc
class Animals(metaclass=abc.ABCMeta): # metaclass是創建類工廠,一般正常的類是type()創建
begin = "這是一個抽象類"
@abc.abstractmethod
def speak(self):
pass
@abc.abstractmethod
def eat():
pass
@abc.abstractclassmethod
def wc(cls):
print('Animal都會上廁所')
@abc.abstractstaticmethod
def sleep():
pass
class Cat(Animals):
def speak(self):
print('Cat都會說話')
def eat():
print('Cat都會吃飯')
@classmethod
def wc(cls):
print('Cat都會上廁所')
@staticmethod
def sleep():
print('Cat都會睡覺')
aa = Cat()
print(aa.begin)
aa.speak()
Cat.eat()
Cat.wc()
aa.sleep()
------------------------------------------------------------------------------------------------------------
接口類:
概念:基於一個接口實現的類,強調函數屬性相似性。
# @Time : 2022/2/23 21:30
# @Author : Bella
# -*- coding: utf-8 -*-
# 1. 普通方式實現接口類
"""
如果調用接口類運行時,沒有接口類中定義的方法會提示報錯
AttributeError: 'WeChat' object has no attribute 'pay'
"""
class WeChat(object):
def pays(self, money):
print('使用微信付款' + str(money))
class ZhiFuBao(object):
def pay(self, money):
print('使用支付寶付款' + str(money))
def pay(PayWay, money):
PayWay.pay(money)
dd = WeChat()
pay(dd, 50)
----------------------------------------------------------------------------------------------------
抽象類和接口類合並:
# @Time : 2022/2/23 21:49
# @Author : Bella
# -*- coding: utf-8 -*-
import abc
"""
利用抽象類,子類必須繼承抽象類中定義的方法的強制性
使得代碼不會出現類中方法名不一樣、或者遺漏的低級錯誤
"""
class AbsInterface(metaclass=abc.ABCMeta):
@abc.abstractmethod
def pay(self, money):
pass
class WeChat(AbsInterface):
def pay(self, money):
print('使用微信付款' + str(money))
class ZhiFuBao(AbsInterface):
def pay(self, money):
print('使用支付寶付款' + str(money))
def Interface(PayWay, money):
PayWay.pay(money)
dd = WeChat()
Interface(dd, 50)