您的位置:首页 > 编程语言 > Python开发

python 面向对象中一些常用内建函数【getattr(), setattr(). hasattr(). delattr()...】

2014-03-02 22:02 731 查看
1.issubclass(sub,parent) #判断sub是否为parent的子类,是的话返回True,否则为False
>>> class P(object):
...     pass
...
>>> class C(P):
...     pass
...
>>> issubclass(C,P)
True
2.isinstance(ins,class) #判断ins是否为class的实例,是的话返回True,否则为False
>>> class P(object):
...     pass
...
>>> class C(P):
...     pass
...
>>> c1 = C()
>>> isinstance(c1,C)
True
3.getattr(), setattr(). hasattr(). delattr()
>>> class test(object):
...      def __init__(self):
...          self.flag = 100
...
>>> newins = test()  #类的实例化
>>> hasattr(newins,'flag')  #hasattr 判断实例newins中也就是test(object)中是否有flag这个属性,有则返回True,否则False
True
>>> hasattr(newins,'test')
False
>>> getattr(newins,'flag')  #getattr 获取属性flag的值
100
>>> getattr(newins,'test','sorry to find it') #getattr 获取属性test的值,如果没有test属性,则返回第三个参数
'sorry to find it'
>>> dir(newins)  # dir()列出属性信息,可以看到实例中有flag属性
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'flag']
>>> setattr(newins,'test','hasValue') #setattr 给实例newins设置test属性,其值为hasValue
>>> getattr(newins,'test') #获取到值,返回test的值
'hasValue'
>>> dir(newins) #实例出现test属性
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'flag', 'test']
>>> delattr(newins,'test') #delattr 删除实例的test属性
>>> dir(newins)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'flag']
4.super() # 寻找父类的信息
>>> class P(object):
...     def __init__(self):
...        print 'I am from P'
...
>>> class C(P):
...     def __init__(self):
...       super(C,self).__init__()
...       print 'my parent is P'
...
>>> new = C()
I am from P
my parent is P
5.__init__() ,__del()__
>>> class P(object):
...    def __init__(self):   #类的初始函数,在声明实例是自动调用该函数
...      print 'initializing...'
...
>>> new = P()
initializing...
>>> class C(P):
...    def __del__(self):  #类的解构函数,删除实例,引用为0时,自动调用该函数
...       print 'finished'
...
>>> new = C()
initializing...
>>> del new
finished
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: