Python基础(九) type元类

python元类:type()   python

元类是python高阶语法. 合理的使用能够减小大量重复性的代码.mysql

 

元类实际上作了如下三方面的工做:sql

 

  • 干涉建立类的过程
  • 修改类
  • 返回修改以后的类

 

为何使用元类?

 

为何要使用元类这种模糊且容易出错的功能?
通常状况下,咱们并不会使用元类,99%的开发者并不会用到元类,因此通常不用考虑这个问题。
元类主用用于建立API,一个典型的例子就是Django的ORM。
它让咱们能够这样定义一个类:数据库

 

class Person(models.Model):
  name = models.CharField(max_length=30)
  age = models.IntegerField()

 

运行下面的代码:函数

guy = Person(name='bob', age='35')
print(guy.age)

返回的结果是int类型而不是IntegerField对象。这是由于models.Model使用了元类,它会将Python中定义的字段转换成数据库中的字段。
经过使用元类,Django将复杂的接口转换成简单的接口。学习

 

原型:type(类名,基类元组(能够为空,用于继承), 包含属性或函数的字典)fetch

 如下两种写法均可以:spa

type('Class',(object,),dict(hello=fun()))code

type('Class',(object,),{"hello":fun()})对象

一、class 自定义的类名称

二、(object,)是继承类,的元组,若是只有一个就写这种形势(object,);多个(object,xxxx,)

三、dict(hello=fun()) 或 {"hello":fun()} 第三个参数,是一个字典等号左是 自定义的方法名,右侧是已写好的方法名,这个要注意,有参数且没有默认值的状况下,要加括号;

 

def fun():
    print('hello world!')


if __name__=="__main__":

    h = type('Hello',(object,),dict(hello=fun()))
    tc = h()
    tc.hello

 

引用:

h 至关于接收Hello类;tc = h()实例化类;tc.hello方法,调用的实际上是咱们定义的fun方法。

    Hello = type('Hello',(object,),dict(hello=fun()))
    tc = Hello()
    tc.hello

 type()动态建立类后,还能够添加更多的方法和属性:

def mysql():
    conn = pymysql.connect(host='127.0.0.1',port=3306 ,user='root' ,passwd='q123456' ,db='amsql' )
    cur = conn.cursor()
    sql = "SELECT * FROM amt_case_interface_table"
    ret = cur.execute(sql)
    print(cur.fetchmany(3))
    #conn.commit()

    cur.close()
    conn.close()
Hello.mysql = mysql()

调用:

tc.mysql

 

Linux and python学习交流1,2群已满.

Linux and python学习交流3群新开,欢迎加入,一块儿学习.qq 3群:563227894

不前进,不倒退,中止的状态是没有的.

一块儿进步,与君共勉,

相关文章
相关标签/搜索