小编bub*_*bba的帖子

Python API设计中的重载(或替代)

我有一个现有的大型程序库,目前有一个.NET绑定,我正在考虑编写一个Python绑定.现有API广泛使用基于签名的重载.所以,我有很多静态函数集合,如:

Circle(p1, p2, p3) -- Creates a circle through three points
Circle(p, r)       -- Creates a circle with given center point and radius
Circle(c1, c2, c3) -- Creates a circle tangent to three curves
Run Code Online (Sandbox Code Playgroud)

在某些情况下,必须以不同的方式使用相同的输入,因此基于签名的重载不起作用,而我必须使用不同的函数名称.例如

BezierCurve(p1,p2,p3,p4) -- Bezier curve using given points as control points
BezierCurveThroughPoints(p1,p2,p3,p4) -- Bezier curve passing through given points
Run Code Online (Sandbox Code Playgroud)

我想第二种技术(使用不同的函数名称)可以在Python API中的任何地方使用.所以,我会的

CircleThroughThreePoints(p1, p2, p3)
CircleCenterRadius(p, r)
CircleTangentThreeCurves(c1, c2, c3)
Run Code Online (Sandbox Code Playgroud)

但这些名字看起来令人不快(我不喜欢缩写),而发明所有这些将是一个相当大的挑战,因为该库有数千个功能.

低优先级:
努力(就我而言) - 我不在乎是否需要编写大量代码.
性能

高优先级:
易于使用/理解呼叫者(许多人将编程新手).
我很容易写出好的文档.
简单 - 避免在调用者代码中使用高级概念.

我确信我不是第一个希望在Python中使用基于签名的重载的人.人们通常使用哪些解决方法?

python overloading

5
推荐指数
3
解决办法
559
查看次数

空抓块

有一个库(我无法控制)包含一个名为Inner的函数,它引发了类型为StupidException的异常.我正在编写一个名为Outer的函数,它调用Inner.我不能提前告诉我什么时候会引发StupidException,我无法以任何合理的方式处理它.我不希望我的函数Outer的调用者看到StupidException - 我将通过从Outer返回null来传达这种情况(由于几个原因).所以,在我看来,最合理的代码是:

public thing Outer()
{
  thing result = null;
  try
  {
     result = Inner();
  }
  catch(StupidException ex)
  {
     // do nothing
  }
  return result;
}
Run Code Online (Sandbox Code Playgroud)

我已经阅读了关于空陷阱是如何邪恶的严厉警告,因为它"吞下"异常.吞下异常正是我想要做的事情,实际上,这里空的捕获块对我来说仍然感觉不对.有没有更好的办法?

c# try-catch

3
推荐指数
1
解决办法
980
查看次数

标签 统计

c# ×1

overloading ×1

python ×1

try-catch ×1