python元类

Welcome to today’s tutorial on python metaclass. We all know that python is an object oriented programming language which means it binds datas with functionalities i.e. class. Before starting about python metaclass we hope you know the concept of class and inheritance. If you don’t have the idea, then you can learn python class and python inheritance first.

欢迎来到有关python metaclass的今天教程。 众所周知,python是一种面向对象的编程语言,这意味着它将数据与类(即类)绑定在一起。 希望在开始介绍python metaclass之前,我们希望您了解类和继承的概念。 如果您不了解,可以先学习python类和python继承 。

Python元类 (Python Metaclass)

Python metaclass is a class that instantiates a class. In python, a class is actually an object of another class. This another class is called metaclass. Metaclass in python defines the behaviors of class objects. let’s look at some examples to understand the metaclass concept clearly.

Python元类是实例化一个类的类。 在python中,一个类实际上是另一个类的对象。 这另一个类称为元类。 python中的元类定义了类对象的行为。 让我们看一些例子,以清楚地了解元类的概念。

Python内置的元类 (Python built-in Metaclass)

type is a built in metaclass in python. Let’s start with the following example:

type是python中的内置元类。 让我们从以下示例开始:

class SampleClass():pass
obj = SampleClass()
print(type(obj))

In the above code we have created a class named SampleClass, and creating an object of it. Then type of object says:

在上面的代码中,我们创建了一个名为SampleClass的类,并创建了一个对象。 然后对象类型说:

class '__main__.SampleClass'

That means obj is an object of SampleClass. Now if we try to see the type of SampleClass itself as following:

这意味着objSampleClass的对象。 现在,如果我们尝试查看SampleClass本身的类型,如下所示:

print(type(SampleClass))

Then the output is:

然后输出是:

class 'type'

That means SampleClass is an object of class type. To be more specific SampleClass is an instance of class type. So type is a metaclass. Every class of python belongs to the built-in metaclass type.

这意味着SampleClass是类type的对象。 更具体地说, SampleClass是类type的实例。 所以type是一个元类。 python的每个类都属于内置的metaclass type

python metaclass如何工作? (How python metaclass works?)

Whenever we create any class then the default metaclass gets called. This metaclass gets called with three information – name of the class, set of base classes of the class and the attributes of the class.

每当我们创建任何类时,都会调用默认的元类。 通过三个信息调用该元类-类的名称,类的基类集和类的属性。

As type is the builtin metaclass, whenever we create a class type gets called with these three argument.

由于type是内置的元类,因此每当我们创建类时,都会使用这三个参数来调用类型。

We are saying that every class in python is also a object of type, which means we can create any class in a single line just like we create object of any class. This way of creating a class is called “creating class on the fly”.

我们说的是python中的每个类也是type的对象,这意味着我们可以在一行中创建任何类,就像我们创建任何类的对象一样。 这种创建类的方式称为“即时创建类”。

使用元类创建python类 (Create python Class using metaclass)

So using the metaclass type, you can create your class in a single line by calling as following:

因此,使用metaclass type ,您可以通过调用以下内容在一行中创建您的类:

Student = type('Student', (), {})

This will create a class named Student at run time of the code. The above line is equivalent to the following code:

这将在代码运行时创建一个名为Student的类。 上一行等效于以下代码:

class Student:pass

If inherits some other class say for example Department then we write as following,

如果继承其他某个类,例如Department,那么我们编写如下,

class Student(Department):pass

Inherited classes should be provided in the second argument when creating class on the fly,

动态创建类时,应在第二个参数中提供继承的类,

Student = type('Student', (Department,), {})

If Student class contains some attributes and functions then they should be provided in the 3rd argument as key value pair. See following the examples:

如果Student类包含一些属性和函数,则应在第3个参数中将它们作为键值对提供。 请参阅以下示例:

class Student:def __init__(self, name, roll):self.name = nameself.roll = rollself.marks = 0.0

Those attributes and functions can be added as following:

可以按以下方式添加这些属性和功能:

def init(self, name, roll):self.name = nameself.roll = rollself.marks = 0.0Student = type('Student', (), {'__init__' : init})

Notice that we have defined the function before we use it. One more thing I want you to understand is that the first argument is class name. So if you write as following:

注意,在使用函数之前,我们已经定义了该函数。 我想让您理解的另一件事是,第一个参数是类名。 因此,如果您编写如下:

Student = type('StudentClass', (), {'__init__' : init})
obj = Student("Zinia", "59")
print(obj.__class__)

Then the output will be,

然后输出将是

class '__main__.StudentClass'

So, it’s better to keep the same name for class and variable to keep consistency.

因此,最好为类和变量保持相同的名称,以保持一致性。

设置元类 (Set the metaclass)

You can set your class’s metaclass explicitly. Whenever python gets the keyword class then it searches for the metaclass. If not found then the default metaclass type is used to create the object of the class. You can set metaclass of your class using the __metaclass__ attribute as following:

您可以显式设置类的元类。 每当python获取关键字class时,它都会搜索元类。 如果未找到,则使用默认的元类类型来创建该类的对象。 您可以使用__metaclass__属性来设置类的元类,如下所示:

class SomeClass:__metaclass__ = type# other methods...print(SomeClass.__metaclass__)

It will produce output as;

它将产生如下输出:

class 'type'

在Python中创建元类 (Creating Metaclass in Python)

Finally, you can also create your own metaclass to define the behaviour of any class that are created using your class.

最后,您还可以创建自己的元类来定义使用该类创建的任何类的行为。

To do that your class must inherit the default metaclass type as this is the main metaclass. See the following example:

为此,您的类必须继承默认的元类type因为这是主要的元类。 请参见以下示例:

It will output:

它将输出:

Python metaclass is a very complicated topic. Here we have given the basic idea of metaclass. Hope now, you do understand the basic concept of metaclass. To understand the functionalities of metaclass you have to go very deep. However you should be aware of how python classes work and what is the role of metaclass in python.

Python元类是一个非常复杂的主题。 这里我们给出了元类的基本思想。 希望现在,您确实了解元类的基本概念。 要了解元类的功能,您必须非常深入。 但是,您应该了解python类的工作方式以及metaclass在python中的作用。

翻译自: https://www.journaldev.com/15505/python-metaclass

python元类

python元类_Python元类相关推荐

  1. python元编程_python元编程详解(3)

    今天转载一片非常精彩的文章供大家欣赏:参考文章链接. python开发者门户一个很好的学习python的网站,大家有时间可以多看看. 下面正式开始今天的内容: 在理解元类之前,你需要先掌握Python ...

  2. python 数据类_python数据类

    前言 之前有写过一篇python元类的笔记,元类主要作用就是在要创建的类中使用参数metaclass=YourMetaclass调用自定义的元类,这样就可以为所有调用了这个元类的类添加相同的属性了. ...

  3. python 新式类和旧式类_python新式类和旧式类区别

    python的新式类是2.2版本引进来的,我们可以将之前的类叫做经典类或者旧式类. 为什么要在2.2中引进new style class呢?官方给的解释是: 为了统一类(class)和类型(type) ...

  4. python经典类新式类_Python新式类与经典类(旧式类)的区别

    看写poc的时候看到的,思考了半天,现在解决了 转载自http://blog.csdn.net/zimou5581/article/details/53053775 Python中类分两种:旧式类和新 ...

  5. python面向对象类_python:面向对象(类)

    #!usr/bin/env python # -*- coding:utf-8 -*- __author__ = "Samson" ###类变量与实例变量 class Role: ...

  6. python 新式类 旧式类_Python新式类与经典类(旧式类)的区别

    Python中类分两种:旧式类和新式类: ➤新式类都从object继承,经典类不需要. ➤新式类的MRO(method resolution order 基类搜索顺序)算法采用C3算法广度优先搜索,而 ...

  7. python新式类好还是经典类_python新式类和经典类的区别?

    python新式类和经典类的区别? 1)首先,写法不一样: class A: pass class B(object): pass 2)在多继承中,新式类采用广度优先搜索,而旧式类是采用深度优先搜索. ...

  8. python3新式类_python新式类和旧式类区别

    python的新式类是2.2版本引进来的,我们可以将之前的类叫做经典类或者旧式类. 为什么要在2.2中引进new style class呢?官方给的解释是: 为了统一类(class)和类型(type) ...

  9. python3 新式类_python新式类和旧式类区别

    python的新式类是2.2版本引进来的,我们可以将之前的类叫做经典类或者旧式类. 为什么要在2.2中引进new style class呢?官方给的解释是: 为了统一类(class)和类型(type) ...

最新文章

  1. SQL Server Profiler工具
  2. 早餐组合(购买方案)
  3. linux连接磁盘阵列,CentOS/Linux 连接 iSCSI 磁盘阵列
  4. python中全局变量和局部变量详解_Python全局变量与局部变量详解
  5. 前端学习(3347):数组方法的运用和总结稀疏数组
  6. 互联网晚报 | 3月3日 星期三 |​ 淘特宣布上线淘特10元店、淘特100;​A股三大指数集体收涨,多只地产股涨停...
  7. python声明编码_Python 2.x 编码声明:是coding:utf-8还是coding=urf-8呢
  8. 同余定理在算法求解中的应用
  9. SetWindowsHookEx 其他进程的 记录
  10. Ubuntu IPFS小白安装入门教程
  11. Python的Turtle绘制纳兹咩的娘口三三
  12. STM8S103 LCD5110例程带字库
  13. 什么是cs架构和bs架构
  14. “没有存在感”是一种什么感受?
  15. 计算机英语口语900句,日常英语口语900句
  16. 热血格斗场和冷血格斗场
  17. mysql percent_SQL 之 SELECT 之 PERCENT用法介绍
  18. q87芯片组服务器主板,Intel 100系列芯片组详解:史上最良心!
  19. 【报告分享】2022年快手品牌号运营策略手册-磁力引擎(附下载)
  20. svg 地图_一秒带你制作出全国各省市区县地图

热门文章

  1. Okio 1.9简单入门
  2. String和包装类Integer\Double\Long\Float\Character 都是final类型
  3. 同一个页面多个ajax提交,速度缓慢
  4. [转载] python numpy 子数组_Python学习笔记3:Numpy入门
  5. [转载] numpy.inf
  6. [转载] PYTHON 网络编程
  7. [转载] java向匿名内部类传递参数
  8. mysql 联合索引匹配原则
  9. python画决策树
  10. DataBase -- Operator