python 类与对象深度2
比较两个类的两种方法:圆的面积 矩形和圆面积作比较 :
第一种: 通过装饰器来比较两个类:将共同代码抽出, 强制子类 实现area方法
import abc
from functools import total_ordering
import math
@total_ordering
class Shap(metaclass= abc.ABCMeta):
@abc.abstractmethod
def area_res(self):
pass
def __gt__(self, other):
return self.area() > other.area()
def __ge__(self, other):
return self.area() >= other.area()
class Rect(Shap):
def __init__(self,w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
class Circle(Shap):
def __init__(self,r):
self.r = r
def area(self):
return self.r ** 2 *math.pi
c = Circle(4)
r = Rect(1,2)
print(c == r)
第二种方法:
# 求矩形面积
from functools import total_ordering
@total_ordering
class Rect(object):
#
def __init__(self,w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def __str__(self):
# 字符串格式化
# f"" 3.6版本以上支持
return f"({self.w},{self.h})"
def __gt__(self, other):
return self.area() > other.area()
def __ge__(self, other):
return self.area() >= other.area()
# r1 = Rect(1,2)
# r2 = Rect(3,4)
# print(r1)
# print(r2)
# print(r1>r2) # TypeError: '>' not supported between instances of 'Rect' and 'Rect'
# print(r1>r2) # 类与类之间比较 直接报错 添加 __gt__方法 可以比较
# print(r1 >= r2)
# print(r1 <= r2)
"""
圆的面积 矩形和圆面积作比较
"""
import math
class Circle(object):
def __init__(self,r):
self.r = r
def area(self):
return self.r ** 2 *math.pi
# def __gt__(self, other):
# return self.area() > other.area()
#
# def __ge__(self, other):
# return self.area() >= other.area()
c = Circle(2)
r = Rect(2,2)
print("比较:",c == r)