Some function to handle class and its interface info

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}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值