简体   繁体   English

使用isinstance()与duck typing

[英]Using isinstance() versus duck typing

I'm writing an interface to matplotlib , which requires that lists of floats are treated as corresponding to a colour map, but other types of input are treated as specifying a particular colour. 我正在编写一个matplotlib的接口,它要求浮点列表被视为对应于颜色映射,但其他类型的输入被视为指定特定颜色。

To do this, I planned to use matplotlib.colors.colorConverter , which is an instance of a class that converts the other types of input to matplotlib RGBA colour tuples. 为此,我计划使用matplotlib.colors.colorConverter ,它是一个类的实例,它将其他类型的输入转换为matplotlib RGBA颜色元组。 However, it will also convert floats to a grayscale colour map. 但是,它还会将浮动转换为灰度色彩图。 This conflicts with the existing functionality of the package I'm working on and I think that would be undesirable. 这与我正在处理的软件包的现有功能相冲突,我认为这是不可取的。

My question is: is it appropriate/Pythonic to use an isinstance() check prior to using colorConverter to make sure that I don't incorrectly handle lists of floats? 我的问题是:在使用colorConverter之前使用isinstance()检查以确保我没有错误地处理浮动列表是否合适/ Pythonic? Is there a better way that I haven't thought of? 有没有更好的方式我没有想到?

I've read that I should generally code to an interface, but in this case, the interface has functionality that differs from what is required. 我已经读过,我通常应该编写一个接口代码,但在这种情况下,接口的功能与所需的功能不同。

Why not write two separate functions, one that treats its input as a color map, and another that treats its input as a color? 为什么不写两个单独的函数,一个将输入视为颜色映射,另一个将其输入视为颜色? This would be the simplest way to deal with the problem, and would both avoid surprises, and leave you room to expand functionality in the future. 这将是处理问题的最简单方法,既可以避免意外,也可以为将来扩展功能留出空间。

It's a little subjective, but I'd say: in general it's a not a good idea, but here where you're distinguishing between a container and an instance of a class it is appropriate (especially when, say, those classes may themselves be iterable, like tuples or strings and doing it the duck-typing would get quite tricky). 这有点主观,但我会说:一般来说这不是一个好主意,但在这里你要区分一个容器和一个类的实例 合适的(特别是当这些类本身可能是可迭代的,像元组或字符串这样做鸭子打字会变得非常棘手)。

Aside : coding to an interface is generally recommended, but it's far more applicable to the Java-style static languages than Python, where interfaces don't really exist, unless you count abstract base classes and the abc module etc. (much deeper discussion in What's the Python version for “Code against an interface, not an object”? ) 旁白一般建议编码到一个接口,但是除非你把抽象基类和它远远的Java风格的静态语言比Python,在接口不真的存在更适用, abc模块等等(更深入的讨论什么是“针对接口而不是对象的代码”的Python版本?

Hard to say without more details, but it sounds like you're closer to building a facade here than anything, and as such you should be free to use your own (neater / tighter / different) API, insulating users from your underlying implementation (Matplotlib). 很难说没有更多的细节,但听起来你在这里建立一个外观比什么都接近,因此你应该可以自由地使用你自己的(更整洁/更紧密/不同)API,使用户与你的底层实现隔离( Matplotlib)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM