【Python】学习笔记——-8.6、面向对象高级编程:6.使用元类

本文深入探讨了Python中的元类概念,包括如何使用type()函数动态创建类,以及如何利用metaclass来修改类的定义。文章还提供了一个通过metaclass实现的简单ORM框架示例。

type()

动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。

比方说我们要定义一个Hello的class,就写一个hello.py模块:

class Hello(object):
    def hello(self, name='world'):
        print('Hello, %s.' % name)

当Python解释器载入hello模块时,就会依次执行该模块的所有语句,执行结果就是动态创建出一个Hello的class对象,测试如下:

>>> from hello import Hello
>>> h = Hello()
>>> h.hello()
Hello, world.
>>> print(type(Hello))
<class 'type'>
>>> print(type(h))
<class 'hello.Hello'>

type()函数可以查看一个类型或变量的类型,Hello是一个class,它的类型就是type,而h是一个实例,它的类型就是class Hello

我们说class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。

type()函数既可以返回一个对象的类型,又可以创建出新的类型,比如,我们可以通过type()函数创建出Hello类,而无需通过class Hello(object)...的定义:

>>> def fn(self, name='world'): # 先定义函数
...     print('Hello, %s.' % name)
...
>>> Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class
>>> h = Hello()
>>> h.hello()
Hello, world.
>>> print(type(Hello))
<class 'type'>
>>> print(type(h))
<class '__main__.Hello'>

要创建一个class对象,type()函数依次传入3个参数:

  1. class的名称;
  2. 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;
  3. class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。

通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。

正常情况下,我们都用class Xxx...来定义类,但是,type()函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂。

metaclass

除了使用type()动态创建类以外,要控制类的创建行为,还可以使用metaclass。

metaclass,直译为元类,简单的解释就是:

当我们定义了类以后,就可以根据这个类创建出实例,所以:先定义类,然后创建实例。

但是如果我们想创建出类呢?那就必须根据metaclass创建出类,所以:先定义metaclass,然后创建类。

连接起来就是:先定义metaclass,就可以创建类,最后创建实例。

所以,metaclass允许你创建类或者修改类。换句话说,你可以把类看成是metaclass创建出来的“实例”。

metaclass是Python面向对象里最难理解,也是最难使用的魔术代码。正常情况下,你不会碰到需要使用metaclass的情况,所以,以下内容看不懂也没关系,因为基本上你不会用到。

我们先看一个简单的例子,这个metaclass可以给我们自定义的MyList增加一个add方法:

定义ListMetaclass,按照默认习惯,metaclass的类名总是以Metaclass结尾,以便清楚地表示这是一个metaclass:

# metaclass是类的模板,所以必须从`type`类型派生:
class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['add'] = lambda self, value: self.append(value)
        return type.__new__(cls, name, bases, attrs)

有了ListMetaclass,我们在定义类的时候还要指示使用ListMetaclass来定制类,传入关键字参数metaclass

class MyList(list, metaclass=ListMetaclass):
    pass

当我们传入关键字参数metaclass时,魔术就生效了,它指示Python解释器在创建MyList时,要通过ListMetaclass.__new__()来创建,在此,我们可以修改类的定义,比如,加上新的方法,然后,返回修改后的定义。

__new__()方法接收到的参数依次是:

  1. 当前准备创建的类的对象;

  2. 类的名字;

  3. 类继承的父类集合;

  4. 类的方法集合。

测试一下MyList是否可以调用add()方法:

>>> L = MyList()
>>> L.add(1)
>> L
[1]

而普通的list没有add()方法:

>>> L2 = list()
>>> L2.add(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'add'

动态修改有什么意义?直接在MyList定义中写上add()方法不是更简单吗?正常情况下,确实应该直接写,通过metaclass修改纯属变态。

但是,总会遇到需要通过metaclass修改类定义的。ORM就是一个典型的例子。

ORM全称“Object Relational Mapping”,即对象-关系映射,就是把关系数据库的一行映射为一个对象,也就是一个类对应一个表,这样,写代码更简单,不用直接操作SQL语句。

要编写一个ORM框架,所有的类都只能动态定义,因为只有使用者才能根据表的结构定义出对应的类来。

让我们来尝试编写一个ORM框架。

编写底层模块的第一步,就是先把调用接口写出来。比如,使用者如果使用这个ORM框架,想定义一个User类来操作对应的数据库表User,我们期待他写出这样的代码:

class User(Model):
    # 定义类的属性到列的映射:
    id = IntegerField('id')
    name = StringField('username')
    email = StringField('email')
    password = StringField('password')

# 创建一个实例:
u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
# 保存到数据库:
u.save()

其中,父类Model和属性类型StringFieldIntegerField是由ORM框架提供的,剩下的魔术方法比如save()全部由metaclass自动完成。虽然metaclass的编写会比较复杂,但ORM的使用者用起来却异常简单。

现在,我们就按上面的接口来实现该ORM。

首先来定义Field类,它负责保存数据库表的字段名和字段类型:

class Field(object):

    def __init__(self, name, column_type):
        self.name = name
        self.column_type = column_type

    def __str__(self):
        return '<%s:%s>' % (self.__class__.__name__, self.name)

Field的基础上,进一步定义各种类型的Field,比如StringFieldIntegerField等等:

class StringField(Field):

    def __init__(self, name):
        super(StringField, self).__init__(name, 'varchar(100)')

class IntegerField(Field):

    def __init__(self, name):
        super(IntegerField, self).__init__(name, 'bigint')

下一步,就是编写最复杂的ModelMetaclass了:

class ModelMetaclass(type):

    def __new__(cls, name, bases, attrs):
        if name=='Model':
            return type.__new__(cls, name, bases, attrs)
        print('Found model: %s' % name)
        mappings = dict()
        for k, v in attrs.items():
            if isinstance(v, Field):
                print('Found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
        for k in mappings.keys():
            attrs.pop(k)
        attrs['__mappings__'] = mappings # 保存属性和列的映射关系
        attrs['__table__'] = name # 假设表名和类名一致
        return type.__new__(cls, name, bases, attrs)

以及基类Model

class Model(dict, metaclass=ModelMetaclass):

    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

    def save(self):
        fields = []
        params = []
        args = []
        for k, v in self.__mappings__.items():
            fields.append(v.name)
            params.append('?')
            args.append(getattr(self, k, None))
        sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
        print('SQL: %s' % sql)
        print('ARGS: %s' % str(args))

当用户定义一个class User(Model)时,Python解释器首先在当前类User的定义中查找metaclass,如果没有找到,就继续在父类Model中查找metaclass,找到了,就使用Model中定义的metaclassModelMetaclass来创建User类,也就是说,metaclass可以隐式地继承到子类,但子类自己却感觉不到。

ModelMetaclass中,一共做了几件事情:

  1. 排除掉对Model类的修改;

  2. 在当前类(比如User)中查找定义的类的所有属性,如果找到一个Field属性,就把它保存到一个__mappings__的dict中,同时从类属性中删除该Field属性,否则,容易造成运行时错误(实例的属性会遮盖类的同名属性);

  3. 把表名保存到__table__中,这里简化为表名默认为类名。

Model类中,就可以定义各种操作数据库的方法,比如save()delete()find()update等等。

我们实现了save()方法,把一个实例保存到数据库中。因为有表名,属性到字段的映射和属性值的集合,就可以构造出INSERT语句。

编写代码试试:

u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
u.save()

输出如下:

Found model: User
Found mapping: email ==> <StringField:email>
Found mapping: password ==> <StringField:password>
Found mapping: id ==> <IntegerField:uid>
Found mapping: name ==> <StringField:username>
SQL: insert into User (password,email,username,id) values (?,?,?,?)
ARGS: ['my-pwd', 'test@orm.org', 'Michael', 12345]

可以看到,save()方法已经打印出了可执行的SQL语句,以及参数列表,只需要真正连接到数据库,执行该SQL语句,就可以完成真正的功能。

不到100行代码,我们就通过metaclass实现了一个精简的ORM框架。

小结

metaclass是Python中非常具有魔术性的对象,它可以改变类创建时的行为。这种强大的功能使用起来务必小心。

8.4 继 承 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): pass class Cat(Animal): pass dog = Dog() dog.run() cat = Cat() cat.run() 执行结果: Animal is running... Animal is running... #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Dog(Animal): def eat(self): print('Eating ...') dog = Dog() dog.run() dog.eat() 执行结果: Animal is running... Eating ... #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Animal(object): def run(self): print('Animal is running...') def __run(self): print('I am a private method.') 执行语句: dog = Dog() dog.__run() 执行结果: Traceback (most recent call last): File "D:/python/workspace/classextend.py", line 25, in <module> dog.__run() AttributeError: 'Dog' object has no attribute '__run' class Animal(object): def run(self): print('Animal is running...') def jump(self): print('Animal is jumpping....') def __run(self): print('I am a private method.') dog = Dog() dog.run() dog.jump() cat = Cat() cat.run() cat.jump() 执行结果: Animal is running... Animal is jumpping.... Animal is running... Animal is jumpping.... 8.5 多 态 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') 执行语句: dog = Dog() print('实例化Dog') dog.run() cat = Cat() print('实例化Cat') cat.run() 执行结果: 实例化Dog Dog is running... 实例化Cat Cat is running... a = list() # a是list型 b = Animal() # b是Animal型 c = Dog() # c是Dog型 print('a是否为list型:', isinstance(a, list)) print('b是否为Animal型:', isinstance(b, Animal)) print('c是否为Dog型:', isinstance(c, Dog)) 执行结果: a是否为list型: True b是否为Animal型: True c是否为Dog型: True print('c是否为Dog型:', isinstance(c, Dog)) print('c是否为Animal型:',isinstance(c, Animal)) 执行结果: c是否为Dog型: True c是否为Animal型: True #! /usr/bin/python3 # -*- coding:UTF-8 -*- def run_two_times(animal): animal.run() animal.run() run_two_times(Animal()) 执行结果: Animal is running... Animal is running... run_two_times(Dog()) 执行结果: Dog is running... Dog is running... run_two_times(Cat()) 执行结果: Cat is running... Cat is running... #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Bird(Animal): def run(self): print('Bird is flying the sky...') run_two_times(Bird()) 执行结果: Bird is flying the sky... Bird is flying the sky... 8.6 封 装 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name, score): self.name = name self.score = score std = Student('xiaozhi',90) def info(std): print('学生:%s;分数: %s' % (std.name, std.score)) info(std) 执行结果: 学生:xiaozhi;分数: 90 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student0(object): def __init__(self, name, score): self.name = name self.score = score def info(self): print('学生:%s;分数: %s' % (self.name, self.score)) stu = Student0('xiaomeng',95) 执行结果: 学生:xiaomeng;分数: 95 8.7 多重继承 #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Animal(object): pass # 大: class Mammal(Animal): pass class Bird(Animal): pass # 各种动物: class Dog(Mammal): pass class Bat(Mammal): pass class Parrot(Bird): pass class Ostrich(Bird): pass #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Runnable(object): def run(self): print('Running...') class Flyable(object): def fly(self): print('Flying...') class Dog(Mammal, Runnable): pass class Bat(Mammal, Flyable): pass 8.8 获取对象信息 1. 使用type()函数 >>> type(123) <class 'int'> >>> type('abc') <class 'str'> >>> type(None) <class 'NoneType'> >>> type(abs) <class 'builtin_function_or_method'> >>> type(pri_pub) #上一节定义的PrivatePublicMethod <class '__main__.PrivatePublicMethod'> >>> type(123)==type(456) True >>> type(123)==int True >>> type('abc')==type('123') True >>> type('abc')==str True >>> type('abc')==type(123) False >>> import types >>> def func(): ... pass ... >>> type(fn)==types.FunctionType True >>> type(abs)==types.BuiltinFunctionType True >>> type(lambda x: x)==types.LambdaType True >>> type((x for x in range(10)))==types.GeneratorType True 2. 使用isinstance()函数 >>> animal = Animal() >>> dog = Dog() >>> isinstance(dog, Dog) True >>> isinstance(dog, Animal) True >>> isinstance(dog, object) True >>> isinstance(dog, Dog) and isinstance(dog, Animal) True >>> isinstance(animal,Dog ) False >>> isinstance([1, 2, 3], (list, tuple)) True >>> isinstance((1, 2, 3), (list, tuple)) True 3. 使用dir() >>> dir('abc') ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 8.9 的专有方法 1. __str__ #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name): self.name = name print(Student('xiaozhi')) 执行结果: <__main__.Student object at 0x0000000000D64198> #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name): self.name = name def __str__(self): return '学生名称: %s' % self.name print(Student('xiaozhi')) 执行结果: 学生名称: xiaozhi >>> s = Student('xiaozhi') >>> s <__main__.Student object at 0x00000000030EC550> #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Student(object): def __init__(self, name): self.name = name def __str__(self): return '学生名称: %s' % self.name __repr__ = __str__ 在交互模式下执行: >>> s = Student('xiaozhi') >>> s 学生名称: xiaozhi 2. __iter__ #! /usr/bin/python3 # -*- coding:UTF-8 -*- class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器a、b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def __next__(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100000: # 退出循环的条件 raise StopIteration(); return self.a # 返回下一个值 3. __getitem__ >>> Fib()[3] Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> Fib()[3] TypeError: 'Fib' object does not support indexing class Fib(object): def __get分段模拟运行结果给出
最新发布
10-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值