扩展/包装具有更多功能的对象

2024-10-02 20:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的问题解决了我经常遇到的一个问题。基本上,有适配器模式这样的解决方案,但我觉得有点不满意

假设我有一个类Polygon,它实现了一个具有相当多功能的-uhm-polygon。其中许多Polygon存在于我的程序中,有些作为单独的变量,有些则存在于集合结构中

现在,有一个函数需要一个基本上是多边形的参数类型,但是有一些附加的特性。比如说,一个Polygon可以返回一些指标:他的体积、重心和角质量。另外,函数还需要原始Polygon的方法

第一个想法是:

class Polygon:
# defines my polygon

class PolygonWithMetrics(Polygon):
# - extends polygon with the metrics
# - takes Polygon as argument upon construction
# - would need to delegate many functions to Polygon

def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonWithMetrics

# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonWithMetrics(p) # Bummer - problem here...
functionUsingPolygonWithMetrics(p_with_metrics)

问题:需要将许多函数从PolygonWithMetrics委托给原始的Polygon

第二个想法是:

class Polygon:
# defines my polygon

class PolygonMetrics:
# takes a polygon and provides metrics methods on it

def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonMetrics

# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonMetrics(p)
functionUsingPolygonWithMetrics(p, p_with_metrics) # Bummer - problem here...

这个想法将原始的Polygon作为参数,再加上提供度量函数的第二个对象。问题是我需要更改functionUsingPolygonWithMetrics的签名

我真正需要的是一个想法,如何扩展一个现有的具有更多功能的临时对象,而不存在想法1和2中给出的问题

我可以大致想象这样一个想法,工作主要由PolygonWithMetrics完成:

class Polygon:
# defines my polygon

class PolygonWithMetrics(maybe inherits something):
# - takes a Polygon and provides metrics methods on it
# - upon construction, it will take a polygon
# - will expose the full functionality of Polygon automatically

def functionUsingPolygonWithMetrics(p):
# use functions of Polygon and PolygonWithMetrics

# driving code:
p = Polygon(some args here)
... more code ...
p_with_metrics = PolygonWithMetrics(p)
functionUsingPolygonWithMetrics(p)

出现三个问题:

  • 这个图案有名字吗
  • 这是一个好主意,还是我应该采取一些更先进的技术
  • 如何在Python中实现它

Tags: andof函数heremywithcodefunctions