面向對象進階---attr家族

1、 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

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

3、內置函數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)))

4、綜合示例:定製本身的數據類型(繼承)

#建立列表,往列表內插入元素,每一個元素都必須是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)

5、綜合示例:受權的方式定製文件的增刪改查

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)
相關文章
相關標籤/搜索