python中元类用法实例

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Django中利用filter与simple_tag为前端自定义函数的实现方法

前言 Django的模板引擎提供了一般性的功能函数,通过前端可以实现多数的代码逻辑功能,这里称之为一般性,是因为它仅支持大多数常见情况下的函数功能,例如if判断,ifequal对比返回值...

Python随机函数random()使用方法小结

1. random.random()   random.random()方法返回一个随机数,其在0至1的范围之内,以下是其具体用法:   import random   print...

Python操作串口的方法

本文实例讲述了Python操作串口的方法。分享给大家供大家参考。具体如下: 首先需确保安装了serial模块,如果没安装的话就安装一下python-pyserial。 一个Python实...

Python实现将蓝底照片转化为白底照片功能完整实例

Python实现将蓝底照片转化为白底照片功能完整实例

本文实例讲述了Python实现将蓝底照片转化为白底照片功能。分享给大家供大家参考,具体如下: import cv2 import numpy as np img=cv2.imread...

关于numpy中eye和identity的区别详解

两个函数的原型为: np.identity(n, dtype=None) np.eye(N, M=None, k=0, dtype=<type ‘float'>); np.i...