简体   繁体   English

继承与实例

[英]Inheritance and isinstance

I just noticed that 我只是注意到

isinstance(myob, MyClass) 

does not only return True when myob is an instance of MyClass but also if myob is an instance of a class that inherits from MyClass . 不仅在myobMyClass的实例时返回True ,而且在myob是从MyClass继承的类的实例时返回。

To be more clear, consider the following: 为了更加清楚,请考虑以下内容:

class Book(object):
    def __init__(self, cover)
        self._cover = cover

class Novel(Book):
    def __init__(self, cover, category):
        Book.__init__(self, cover)
        self._category = category

When instanciating Novel as follows: 当实例化Novel时,如下所示:

novel = Novel('hardcover', 'police')

then 然后

print(isinstance(novel, Book))

and

print (isinstance(novel , Novel))

both print True . 都打印True

Why is that so? 为什么会这样? In my sense, novel is a Novel instance, not a Book one... 在我看来, novel是一个Novel实例,而不是一Book ...

Also, relevant to this : 另外,与此相关:

In order to get the "grand-mother" (sic) class, I do: 为了获得“祖母”(原文如此)课程,我这样做:

print(novel.__class__.__bases__)

Is there a more direct way? 有没有更直接的方法?

Inheritance is "is a" relationship - if Duck inherit from Bird then obviously a duck (instance of Duck ) is ALSO a bird (instance of Bird ), so the behaviour you observe is really the expected one (and this holds for all class-based OOPLs). 继承是“是”的关系-如果Duck继承Bird则显然鸭子(实例Duck )也是bird (实例Bird ),所以你观察它的动作实在是所预期的(这适用于所有讲座基于OOPL)。

If you want to check the exact type of an object, you can get it using type(obj) - which will return the class of object - and do an identity test against the desired class, ie: 如果要检查对象的确切类型,则可以使用type(obj)获得它-该对象将返回对象的类-并针对所需的类进行身份测试,即:

obj = 42
print(type(obj) is int)

This transitive behavior is how it should work intuitively ... 这种传递行为是它应该如何直观地工作的...

>>> class Text:
...:    pass
...:
...:
>>> class Book(Text):
...:    pass
...:
...:
>>> class Novel(Book):
...:    pass
...:
...:
>>> n = Novel()
>>> isinstance(n, Novel)
>>> True
>>> isinstance(n, Book)
>>> True
>>> isinstance(n, Text)
>>> True

... because a Novel is-a Novel , but also is-a Book and is-a Text . ...因为一Novel 是-一 Novel ,但也是-一 Book一则 Text

If you want to know whether a class (or instance of a class) is a direct ancestor of another class, you can use the __subclasses__ method of class objects. 如果您想知道一个类(或一个类的实例)是否是另一个类的直接祖先,则可以使用类对象的__subclasses__方法。

>>> Text.__subclasses__()
>>> [__main__.Book]
>>> Book.__subclasses__()
>>> [__main__.Novel]
>>> Novel.__subclasses__()
>>> []
>>> 
>>> Novel in Text.__subclasses__()
>>> False
>>> type(n) in Text.__subclasses__()
>>> False
>>> Novel in Book.__subclasses__()
>>> True
>>> type(n) in Book.__subclasses__()
>>> True

edit: YourClass.__bases__ also gives you all direct parent classes. 编辑: YourClass.__bases__还为您提供所有直接的父类。

>>> Novel.__bases__
>>> (__main__.Book,)

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

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