首页 技术 正文
技术 2022年11月11日
0 收藏 772 点赞 2,273 浏览 3479 个字

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

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

class Foo:
passobj=Foo()print(isinstance(obj,Foo))打印结果为
True

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

class Foo(object):
passclass Bar(Foo):
passprint(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)
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849