关于如何检查多态实例是否有共识? [英] Is there a consensus on how to check a polymorphic instance?

查看:71
本文介绍了关于如何检查多态实例是否有共识?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我是一个内置C ++大脑的新手Python程序员。我有一个

轻量级框架,我在其中设计了一个基类,并期望用户延伸到
。在框架的其他部分,我大量使用

这个基类(或其子类)的实例。我怎样才能确保实例

IS-A基类实例,因为Python是一个完全动态的打字

语言?


我搜索并发现了几种不同的方法:


1.在Python中的文本处理中,David Mertz建议使用`hasattr''

检查能力而不是类型检查。


2.在ActiveState的Python Cookbook网站上,Alex Martelli在你面前建议一个

安全准确的`
上的飞跃技术 http:// aspn .activestate.com / ASPN / Coo ... n / Recipe / 52291


3.在这个组中,其他一些人建议使用isinstance()内置

函数来检查实例。


现在我的问题:

1.我的设计是否使用原生Python语言?这样的设计原生于C ++

和Java OO风格,但我不太清楚Python中的这一点。


2.正如我所说的标题,如何检查一个

多态实例是否有共识?我发现上面三种方式都比C ++和Java有点乏味,其中编译时类型检查

确保了接口协议,任何更好的想法Python?

任何评论都将不胜感激。

解决方案

正如你自己所说,很多人在这小组可能会推荐

解决方案#3。我同意他们的意见。


你应该记住,Alex的食谱(解决方案#2)发表在2001年的b $ b bb之前(版本2.2之前)这引入了OO方面的重大变化,所以我不知道他不会再推荐这个解决方案了。我会把它留给他来给他最后的判断。


我没看过Mertz的书,我也没有我知道在什么情况下他推荐

解决方案#1。我个人认为它在你想要的情况下很有用
检查类是否有类似next()的方法,所以你想要

看看对象是否是迭代。但是如果你使用

属性x1实现一个基类,那么检查具有

属性的对象可能会有风险。该对象可能具有该名称的属性,但其角色可能与您期望的完全不同(例如,您的班级可能会使用x1

作为列表,但是您的object是一个类的实例,它使用x1作为

字符串)。方法也一样。


使用isinstance()。这就是它的用途。


Dan


" Mike Meng" <我****** @ gmail.com>在消息中写道

news:11 ********************** @ z14g2000cwz.googlegr oups.com ...

大家好,
我是一个内部有C ++大脑的新手Python程序员。我有一个轻量级的框架,我在其中设计了一个基类并期望用户进行扩展。在框架的其他部分,我大量使用了这个基类(或其子类)的实例。我如何确保实例
IS-A基类实例,因为Python是一种完全动态的类型语言?

我搜索并找到了几种不同的方法:

1.在Python中的文本处理中,David Mertz建议使用`hasattr''
检查能力而不是类型检查。

2.在ActiveState中在Python Cookbook网站上,Alex Martelli在
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52291

3.在这个小组中,其他一些人建议使用isinstance()内置
函数来检查实例。

现在我的问题:
1.我的设计是否使用本机Python?这样的设计本身就是C ++和Java OO风格,但我不太清楚它在Python中的用途。

2.正如我在标题中所述,是否有如何共识检查一个多态实例?我发现上面三种方式与C ++和Java相比有点乏味,其中编译时类型检查确保了接口协议,Python中有哪些更好的想法?
任何评论我将不胜感激。



Mike Meng写道:

我是一名内部有C ++大脑的新手Python程序员。我有一个轻量级的框架,我在其中设计了一个基类并期望用户进行扩展。在框架的其他部分,我大量使用了这个基类(或其子类)的实例。我如何确保实例
IS-A基类实例,因为Python是一种完全动态的类型语言?




简短的回答是如果你想确保一个实例是 - 基类的子类

,你应该使用isinstance:

类HasF(对象):
.... def f(self):

.... raise NotImplementedError

....类SubHasF(HasF):
.... def f(self):

....返回self .__ class__

.. ..类NonsubHasF(对象):
.... def f(self):

....返回self .__ class__

.... isinstance(SubHasF(),HasF)
True isinstance(NonsubHasF(),HasF)
False


但是通常没必要走这条路线。考虑:

类HasNoF(对象):
....传递

.... def use_c(c):
...尝试:

.... f = cf

....除了AttributeError:

....引发TypeError('' use_c的参数必须有f方法'')

....返回f()

.... use_c(SubHasF())
< ; class''__ main __。SubHasF''> use_c(NonsubHasF())
< class''_ _ main __。NonsubHasF''> use_c(HasNoF())



回溯(最近一次调用最后一次):

文件"<交互式输入> ",第1行,在?

文件"<交互式输入>",第5行,在use_c中

TypeError:use_c的参数必须有f方法


是否真的有必要将类传递给你的等价物

''use_c''实际上是等同于''HasF''的子类?或者它是否需要支持适当的方法?
?如果它是

秒,我只会测试适当的方法并捕获

AttributeErrors(可能还有如果'f'引发的TypeError ''不是

可以赎回)。


如果你能详细说明你的具体例子,我(和

其他人)可能会给你更多有用的建议...


史蒂夫


谢谢Dan,
解决方案#1从''Python中的文本处理''结束,部分

1.1.3,`Pythonic Polymorphisim'',在那里,这是一个例子他
提供:


def toDOM(xml_src =无):

来自xml.dom import minidom

if hasattr(xml_src,''documentElement''):

返回xml_src#它已经是一个DOM对象

elif hasattr(xml_src,''read''):

#这是知道如何读取数据的东西

返回minidom.parseStrin g(xml_src.read())

elif type(xml_src)in(StringType,UnicodeType):

#它是XML文档的文件名

xml = open(xml_src).read()

返回minidom.parseString(xml)

else:

引发ValueError," ;必须用初始化+ \

"文件名,类文件对象或DOM对象"

你有什么看法?


hi all,
I''m a newbie Python programmer with a C++ brain inside. I have a
lightweight framework in which I design a base class and expect user to
extend. In other part of the framework, I heavily use the instance of
this base class (or its children class). How can I ensure the instance
IS-A base class instance, since Python is a fully dynamic typing
language?

I searched and found several different ways to do this:

1. In `Text Processing in Python'', David Mertz suggests using `hasattr''
to check abilities instead of type checking.

2. In ActiveState''s Python Cookbook site, Alex Martelli suggested a
safe and accurate `look before you leap'' technique on
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52291

3. In this group, some others suggest using isinstance() builtin
function to check instance.

Now my questions:
1. Is my design speaks native Pythonish? Such design is native in C++
and Java OO style, but I''m not sure about this in Python.

2. As I state in title, is there a consensus on how to check a
polymorphic instance? I find all the three ways above is a little bit
tedious compared with C++ and Java, in which compile-time type checking
ensures the interface protocol, any better ideas in Python?
Any comments will be appreciated.

解决方案

As you say yourself, many people in this group will probably recommend
solution #3. I would agree with them.

You should keep in mind that Alex''s recipe (solution #2) was published in
2001 (before version 2.2 which introduced big changes in terms of OO) so I''m
not sure he would recommend that solution anymore. I''ll leave it to him to
give his final judgement.

I haven''t read Mertz''s book and I don''t know in what context he recommends
solution #1. Personally I see it useful in situations where you want to
check whether the class has a method like next() for example, so you want to
see whether the object is iterable. But if you implement a base class with
an attribute x1 it may be risky to just check objects for having that
attribute. The object may have an attribute with that name but its role may
be completely different than what you expect (e.g., your class may use x1
for a list, but your object is an instance of a class that uses x1 for a
string). Same thing with methods.

Go with isinstance(). That''s what it''s for.

Dan

"Mike Meng" <me******@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...

hi all,
I''m a newbie Python programmer with a C++ brain inside. I have a
lightweight framework in which I design a base class and expect user to
extend. In other part of the framework, I heavily use the instance of
this base class (or its children class). How can I ensure the instance
IS-A base class instance, since Python is a fully dynamic typing
language?

I searched and found several different ways to do this:

1. In `Text Processing in Python'', David Mertz suggests using `hasattr''
to check abilities instead of type checking.

2. In ActiveState''s Python Cookbook site, Alex Martelli suggested a
safe and accurate `look before you leap'' technique on
http://aspn.activestate.com/ASPN/Coo...n/Recipe/52291

3. In this group, some others suggest using isinstance() builtin
function to check instance.

Now my questions:
1. Is my design speaks native Pythonish? Such design is native in C++
and Java OO style, but I''m not sure about this in Python.

2. As I state in title, is there a consensus on how to check a
polymorphic instance? I find all the three ways above is a little bit
tedious compared with C++ and Java, in which compile-time type checking
ensures the interface protocol, any better ideas in Python?
Any comments will be appreciated.



Mike Meng wrote:

I''m a newbie Python programmer with a C++ brain inside. I have a
lightweight framework in which I design a base class and expect user to
extend. In other part of the framework, I heavily use the instance of
this base class (or its children class). How can I ensure the instance
IS-A base class instance, since Python is a fully dynamic typing
language?



The short answer is that if you want to ensure an instance is-a subclass
of the base class, you should use isinstance:

class HasF(object): .... def f(self):
.... raise NotImplementedError
.... class SubHasF(HasF): .... def f(self):
.... return self.__class__
.... class NonsubHasF(object): .... def f(self):
.... return self.__class__
.... isinstance(SubHasF(), HasF) True isinstance(NonsubHasF(), HasF) False

However it''s often not necessary to go this route. Consider:
class HasNoF(object): .... pass
.... def use_c(c): .... try:
.... f = c.f
.... except AttributeError:
.... raise TypeError(''argument to use_c must have an f method'')
.... return f()
.... use_c(SubHasF()) <class ''__main__.SubHasF''> use_c(NonsubHasF()) <class ''__main__.NonsubHasF''> use_c(HasNoF())


Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 5, in use_c
TypeError: argument to use_c must have an f method

Is it really necessary that the classes passed to your equivalent of
''use_c'' are actually subclasses of your equivalent to ''HasF''? Or is it
just necessary that they support the appropriate methods? If it''s the
second, I would just test for the appropriate methods and catch the
AttributeErrors (and possibly the TypeError that''s thrown if ''f'' isn''t
callable).

If you can give a little more detail on your particular example, I (and
others) can probably give you more helpful suggestions...

Steve


Thank you Dan,
Solution #1 is concluded from ''Text Processing in Python'', section
1.1.3, `Pythonic Polymorphisim'', around there, here is an example he
provides:

def toDOM(xml_src = None):
from xml.dom import minidom
if hasattr(xml_src, ''documentElement''):
return xml_src # it''s already a DOM object
elif hasattr(xml_src, ''read''):
# it is something that knows how to read data
return minidom.parseString(xml_src.read())
elif type(xml_src) in (StringType, UnicodeType):
# it is a filename of an XML document
xml = open(xml_src).read()
return minidom.parseString(xml)
else:
raise ValueError, "Must be initialized with " + \
"filename, file-like object, or DOM object"
What''s your opinion?


这篇关于关于如何检查多态实例是否有共识?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆