1) get some class info
the following example show basic inheritance
class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter): # SPAMFilter is a subclass of Filter
def init(self): # Overrides init method from Filter superclass
self.blocked = ['SPAM']
There are some useful functions or methods to know about the inheritance infomation
>>> issubclass(SPAMFilter, Filter) #check subclass
True
>>> issubclass(Filter, SPAMFilter)
False
>>> SPAMFilter.__bases__ #show baseclass info
(<class __main__.Filter at 0x171e40>,)
>>> Filter.__bases__
()
>>> s = SPAMFilter()
>>> isinstance(s, SPAMFilter) #check instance info
True
>>> isinstance(s, Filter)
True
>>> isinstance(s, str)
False
>>> s.__class__ #show class info
<class __main__.SPAMFilter at 0x1707c0>
2) handle Interface info
There are some useful fuction and method to check instance interface infomation.
>>> tc = Filter()
>>> hasattr(tc, 'filter') #check whether the required methods are present.
True
>>> hasattr(tc, 'haha')
False
>>> callable(getattr(tc, 'filter', None)) # check whether the talk attribute was callable
True
>>> callable(getattr(tc, 'haha', None))
False
The function callable is no longer available in Python 3.0. Instead of callable(x), you can use hasattr(x, '__call__').
The inverse of getattr is setattr, which can be used to set the attributes of an object:
>>> setattr(tc, 'newAttr', 'xixi')
>>> tc.newAttr
'xixi'
if you want to see all the values store in an object, you can examines its __dict__ attrbute.
>>>SPAMFilter.__dict__
{'__module__': '__main__', 'init': <function init at 0xb71ffa74>, '__doc__': None}
>>>Filter.__dict__
{'filter': <function filter at 0xb71ffaac>, '__module__': '__main__', 'init': <function init at 0xb71ff72c>, '__doc__': None}