绑定,反射,内置函数
#绑定方法:绑定给谁就应该谁来调用,谁来调用就会把谁当做第一个参数自动传入
import setting #配置文件为setting
class MySQL:
def __init__(self,host,port): #绑定到对象
self.host=host
self.port=port
@classmethod #绑定到类
def from_conf(cls):
return cls(setting.HOST,setting.PORT)
@staticmethod #不与类也不与对象绑定
def creat_id():
n=eroos
return n
con=mysql.from_conf()
print(con.port,con.host)
com=mysql.creat_id()
print(com.create_id)
#反射 通过字符串来操作对象或者类的属性 1.hasattr 2.setattr 3.getattr 4.delattr
class foo:
def __init__(self,name):
self.name=name
def f1(self):
print('f1')
obj=foo('abc')
#hasattr() 判断
print(hasattr(obj,'name'))
print(hasattr(obj,'f1'))
#getattr 调用
if hasattr(obj,'f1'):
f=getattr(obj,'f1')
#print(f)
f()
#setattr() 修改
obj.x=1
setattr(obj,'x',2)
print(obj.__dict__)
#delattr 删除
#del obj.name
delattr(obj,'name')
print(obj.__dict__)
class fprser:
def __init__(self,host,port):
self.host=host
self.port=port
self.conn='xxx'
def intera(self):
while True:
cmd=input('>>: ').strip()
if not cmd:continue
cmd_l=cmd.split()
print(cmd_l)
if hasattr(self,cmd_l[0]):
func=getattr(self,cmd_l[0])
func(cmd_l)
def get(self,cmd_l):
print('geting......',cmd_l)
def put(self,cmd_l):
print('puting...',cmd_l)
client=fprser('2.2.2.2',23)
client.intera()
#内置函数
isinstance() #判断一个对象是不是某个类型的
l=list([])
print(isinstance(l,list))
issubclass() #判断是不是某个的子类
class foo:
pass
class bar(foo):
pass
print(issubclass(bar,foo))
#__str__ #打印时触发,默认打印内存地址
class foo:
def __init__(self,name,age): #初始化时触发
self.name=name
self.age=age
def __str__(self): ##打印时触发
return <__main__,.......> #可以修改打印自己需要的
conf=foo('abc',38)
print(conf) #print(abc.__str__())
#__del__ 回收之后在打印del
class foo:
def __del__(self):
print('del....')
obj=foo()
print('123')
class foo:
def __del__(self):
print('del....')
obj = foo()
del obj
print('123')
文章名称:绑定,反射,内置函数
网页链接:http://scyanting.com/article/jocgpe.html