Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of issubclass

Tags:

python

>>> import sys
>>> sys.version_info
(2, 4, 4, 'final', 0)
>>> class C:
...    pass
...
>>> issubclass(C, C)
True
>>> issubclass(C, object)
False
>>> class T(object):
...    pass
...
>>> issubclass(T, T)
True
>>> issubclass(T, object)
True
>>>

Question 1> Why C is a subclass of C?

Question 2> what is the base class of C?

Thank you

// Update for Chris Morgan (At least for me, the following manual doesn't help at all)

>>> help(issubclass)
Help on built-in function issubclass in module __builtin__:

issubclass(...)
    issubclass(C, B) -> bool

    Return whether class C is a subclass (i.e., a derived class) of class B.
    When using a tuple as the second argument issubclass(X, (A, B, ...)),
    is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).
like image 798
q0987 Avatar asked Jan 17 '23 12:01

q0987


2 Answers

Take a look at issubclass(class, classinfo) documentation

Return true if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

and to check base class of C use inspect.getmro(cls) function.

Return a tuple of class cls’s base classes, including cls, in method resolution order.

   >>> class C(object):
...        pass
...
>>> inspect.getmro(C)
(<class '__main__.C'>, <type 'object'>)
>>>
like image 84
RanRag Avatar answered Jan 29 '23 18:01

RanRag


http://docs.python.org/library/functions.html#issubclass From that link, "A class is considered a subclass of itself."

To answer your second question, C is an "old style" class so it isn't a subclass of object. Include object as the superclass if you want a new style class. See http://www.python.org/doc/newstyle/ for more info.

like image 30
gfortune Avatar answered Jan 29 '23 19:01

gfortune