补充内置函数
1.isinstance判断是否是 foo这个类的实例,也可以用来判断数据类型
class foo:
pass
obj=foo()
print(isinstance(obj,foo))
d={'x':1}
print(isinstance(d,dict))
2.issubclass判断是不是他的子类
class parent:
pass
class sub(parent):
pass
print(issubclass(sub,parent)) #判断sub是不是parent的子类
print(issubclass(parent,object)) #判断parent是不是object的子类
反射
class people:
country="china"
def __init__(self,name):
self.name=name
def eat(self):
print('%s is eating'%self.name)
peo1=people('egon')
#操作属性
print(people.country)#表示访问
peo1.name=1 #表示赋值
# del peo1.name#表示删除
print(peo1.__dict__)
print(peo1.country)
print(people.__dict__)
1、什么是反射
通过字符串来操作类或者对象的属性
2、如何用
hasattr,getattr,setattr,delattr
class people:
country="china"
def __init__(self,name):
self.name=name
def eat(self):
print('%s is eating'%self.name)
peo1=people('egon')
#操作属性
print(people.country)#表示访问
peo1.name=1 #表示赋值
# del peo1.name#表示删除
print(peo1.__dict__)
print(peo1.country)
print(people.__dict__)
print(hasattr(peo1,'xxx'))#'xxx in peo1.__dict__ 判断peo1是否有这个属性
print(getattr(peo1,'xxxx','没有哇'))
setattr(peo1,'age',18)#peo1.age=18 设置
delattr(peo1,'name')
print(peo1.__dict__)
delattr(peo1,'name')
class ftp:
def __init__(self,ip,port):
self.ip=ip
self.port=port
def get(self):
print('get function')
def put(self):
print('put function')
def run(self):
while True:
choice=input('>>请输入相关数据').strip()
# print(choice,type(choice))
# if hasattr(self,choice):
# method=getattr(self,choice)
# method()
# else:
# print('输入的名字不存在')
method=getattr(self,choice,None)
if method is None:
print('输入的命令不存在')
else:
method()
conn=ftp('1.1.1.1',23)
conn.run()
内置的方法 满足某种条件下自动触发从而实现某种功能
定制__str__方法控制对象的打印格式
class people:
def __init__(self,name,age): #杠杠开头杠杠结尾都是满足某种条件下自动触发
self.name=name
self.age=age
#在对象self被打印时,自动触发,应该在该方法内
def __str__(self):
print('ok',self)
# return '我草尼玛沐风'
obj=people('egon',18)
print(obj)
1、什么是元类
在python中一切皆对象,那么我们用class关键字定义的类本身也是一个对象
负责产生该对象的类称之为元类,即元类可以简称为类的类
class Foo: # Foo=元类()
pass
2、为何要用元类
元类是负责产生类的,所以我们学习元类或者自定义元类的目的
是为了控制类的产生过程,还可以控制对象的产生过程
3、如何用元类