type()、获取对象信息

1.判断对象类型 type()

type(obj)返回对线类型如:
type(1)     #<class 'int'>
type('a') #<class 'str'>
func():
    return ('this is a function')
type(func)  #<class 'function'>

2.和 isinstance()区别

class Father():
    pass
class Child(Father):
    pass

isinstance(Child(),Father)#子类也是父类的实例  返回True
type(Child())==Father # 子类不属于父类类型  返回False

3.type的另外一个作用,动态生成类

class A():
    def say():
        return ('function say')

type(A())#<class '__main__.A'>
type(A)#<class 'type'>

我们发现type(A)输出的是type类型,python动态语言中的类是在运行时候创建的,而创建class的方法就是type()方法
python中类创建的本质:
我们使用class创建类,当你使用class关键字时,Python解释器自动创建这个对象。而底层其实使用的是type函数(type函数也可以查看实例所属类型)来创建类的。所以我们可以直接使用type()函数来手动实现动态创建类。
type()创建类的语法为:
类名 = type('字符串类型,同类名',(继承关系,元祖类型),{字典类型,放类的方法 和类属性})
举例说明:

class Person():
    def per(self):
        return('这是Person类中的per方法')
class Test_obj():
    def func1(self):
        return('另外的一个func1函数')
# Student=type('Student',(Person,),dict(say=Test_obj().func1))
Student=type('Student',(Person,),{'say':Test_obj().func1,'name':'jack'})
stu=Student()
print(stu.per())#这是Person类中的per方法
print(stu.say())#另外的一个func1函数
print(stu.name)#jack    

这个动态生成的类等同于:

class Student(Person):
    name = 'jack'
    def say(self):
        return('另外的一个func1函数')

4.hasattr getattr setattr

其实我们也不用像上述代码那样子 一个一个打印出来来验证申明的类中是否有这些属性.

查看是否含有某个属性,可以用 hasattr(obj,attr)

接上述代码:

    hasattr(Student,'per')  #True
    hasattr(Student,'name')#True
    hasattr(Student,'say')#True

当传一个没有的属性时,返回False

  hasattr(Student,'score')#False

获取某个属性,可以用getattr(obj,attr)

    getattr(Student,'name') #jack
    getattr(Student,'per')#<function Person.per at 0x000001FE7208D948> 返回这个函数    

当试图获取一个没有的属性的时候,报错

  getattr(Student,'score')#报错没有属性score

当然我们一般都是直接去obj.attr 去获取属性,没必要去getattr,hasattr但是当我们不知道对象信息的时候,getattr就起作用了,如:

def readImage(fp):
  if hasattr(fp, 'read'):
     return readData(fp)
  return None

假设我们希望从文件流 fp 中读取图像,我们首先要判断该 fp 对象是否存在 read 方法,如果存在,则该对象是一个流,如果不存在,则无法读取。hasattr()就派上了用场。根据鸭子类型,有 read()方法,不代表该 fp 对象就是一个文件流,它也可能是网络流,也可能是内存中的一个字节流,但只要 read()方法返回的是有效的图像数据,就不影响读取图像的功能。

当然我们也可以去setattr手动给某个类添加属性 :setattr(objname,attrname,attr)

还是接上述动态生成的Student类 如:

    setattr(Student,'score',100)
    hasattr(Student,'score')  #True
    def func2(self):
        return ('func2')
    setattr(Student,'func2',func2)
    Student().func2()    #返回func2

当setattr一个属性和之前本来就存在的属性同名的时候,直接覆盖原来的属性

posted @ 2020-09-17 15:37  Alantammm  阅读(273)  评论(0编辑  收藏  举报