面向对象进阶---attr家族

一、 isinstance(obj,cls)和issubclass(sub,super)

isinstance(obj,cls)检查obj是否是类 cls 的对象

class Foo:
    pass

obj=Foo()

print(isinstance(obj,Foo))

打印结果为
True

issubclass(sub, super)检查sub类是否是 super 类的派生类

class Foo(object):
    pass

class Bar(Foo):
    pass

print(issubclass(Bar, Foo))

d打印结果为
True

二、反射

1、概念:主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)

2、四个实现反射的函数:都是通过字符串的形式

(1)hasattr(object,name):判断object中有没有一个name字符串对应的方法或属性
def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass
(2)getattr(object,name):查看类object中的name字符串对应的值
def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass
(3)setattr(object,name,value):将object中name字符串的值设置为value
def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.

    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass
(4)delattr(object,name):删除object类中的name字符串属性
def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.

    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass
(5)综合示例
class People:
    country='China'
    def __init__(self,name):
        self.name=name
    def walk(self):
        print('%s is walking' %self.name)
p=People('egon')

print('name' in p.__dict__)
print(hasattr(p,'name'))            #hasattr查看是p实例内是否有name属性
print(hasattr(p,'country'))
print(hasattr(People,'__init__'))
print(getattr(p,'walk'))            #getattr查看p对象内walk的属性值

res=getattr(p,'country')  #getattr获取属性
print(res)

getattr(p,'xxxxxxxxx','这个属性不存在')  #可以指定返回值,如果要找的属性不存在,会返回指定的字符串


setattr(p,'country','123')  #setattr修改
print(getattr(p,'country'))

delattr(p,'country')   #delattr删除p对象内的country
print(hasattr(p,'country'))    #查看p对象内还有没有country

打印结果如下
True
True
True
True
<bound method People.walk of <__main__.People object at 0x00000000010847F0>>
China
123
True

三、内置函数attr(setattr,getattr,delattr)

#setattr:设置属性
# getattr:查找属性,只在对象不存在的情况下才触发
# delattr:删除属性
#这些内置方法只是确定了class的调用方法,具体的操作需要def 内部的代码
class Foo:
    def __init__(self,name):
        self.name=name

    def __setattr__(self, key, value):  #设置
        print('-----setattr---key:%s,value:%s'%(key,value))
        print(type(key))
        print(type(value))
        self.__dict__[key]=value
    def __delattr__(self, item):   #删除
        print('delattr:%s' %item)
        del self.__dict__[item]

    def __getattr__(self, item):  #属性不存在的情况下才会触发
        print('getattr-->%s %s' %(item,type(item)))

四、综合示例:定制自己的数据类型(继承)

#创建列表,往列表内插入元素,每个元素都必须是int
class List(list):                   #创建List类,继承list
    def append(self, p_object):     #append函数
        print('------>',p_object)
        if not isinstance(p_object,int):   #如果p_object不是int,返回类型错误
            raise TypeError('必须是整型')
        super().append(p_object)           #如果是int,调用父类(list)的append方法将值插入列表

    def insert(self,index,p_object):      #定义一个insert函数
        if not isinstance(p_object,int):
            raise TypeError('必须是整型')
        super().insert(index,p_object)        



l=List([1,2,3])
print(l)
l.append(4)
print(l)
l.insert(4,5)
print(l)

五、综合示例:授权的方式定制文件的增删改查

import time
class Open:
    def __init__(self,filepath,mode='r',encoding='utf8'):
        self.filepath=filepath
        self.mode=mode
        self.encoding=encoding
        self.x=open(filepath,mode=mode,encoding=encoding)

    def write(self,line):
        t=time.strftime('%Y-%m-%d %x')
        self.x.write('%s %s' %(t,line))
    def __getattr__(self, item):
        return getattr(self.x,item)
        
f=Open('b.txt','w')
f.write('1111111\n')
f.write('2222222\n')
f.write('3333333\n')
f.write('3333333\n')
f.close()

f=Open('b.txt','r+')
# f.seek(0)
res=f.read()
print(res)
posted @ 2017-04-24 15:41  f_manito  阅读(310)  评论(0编辑  收藏  举报