Home > Backend Development > Python Tutorial > python中元类用法实例

python中元类用法实例

WBOY
Release: 2016-06-16 08:41:10
Original
1204 people have browsed it

本文实例讲述了python中元类用法,分享给大家供大家参考。具体方法分析如下:

1.元类(metaclass)是用来创建类的类

2.type(object):返回一个对象的类型,与object.__class__的值相同,type(name,bases,dict):创建一个新的type类型,name就是新class的name,值存到__name__属性中,bases是tuple类型,值会存到__bases__中,dict的值存到__dict__中

复制代码 代码如下:
class X:
...     a = 1
...
X = type('X', (object,), dict(a=1))

3.类默认是用type()创建的,通过定义类时指定metaclass参数或继承自某个类,而该类指定了metaclass参数,可以自定义类的创建过程

复制代码 代码如下:
class OrderedClass(type):
     #该方法返回值就是__new__的namespace参数,如果没有该方法namespace的值就是dict()
     @classmethod
     def __prepare__(metacls, name, bases, **kwds):
        return collections.OrderedDict()
     #namespace就是class的__dict__,这个dict类型的对象已经被填充了相应的值
     def __new__(cls, name, bases, namespace, **kwds):
        result = type.__new__(cls, name, bases, dict(namespace))
        result.members = tuple(namespace)
        return result

class A(metaclass=OrderedClass):
    def one(self): pass
    def two(self): pass
    def three(self): pass
    def four(self): pass
print(A.members)
#('__module__', '__qualname__', 'one', 'two', 'three', 'four')

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template