简体   繁体   English

如何在python中使用自定义元类构造动态类?

[英]How to construct dynamical class with custom metaclass in python?

As I read in documentation I can create class dynamically but how to replace this class metaclass? 在阅读文档时,我可以动态创建类,但是如何替换此类的元类呢?

Should I just replace type metaclass with SomeMetaClass ? 我应该只用SomeMetaClass替换type metaclass吗?

The question is very simple but simple help will be welcome too. 这个问题很简单,但也欢迎简单的帮助。

As I see, you want to change the metaclass after class creation. 如我所见,您想在类创建后更改元类。 If so, you can achieve it in the same way that you can change the class of an object. 如果是这样,您可以通过与更改对象的类相同的方式来实现它。 For starters, the initial metaclass needs to be different from type, the __init__ and __new__ of the new metaclass won't be called (though you can manually call __init__ or a method that performs __init__ 's job). 对于初学者,初始元类必须与类型不同,新元类的__init____new__不会被调用(尽管您可以手动调用__init__或执行__init__的工作的方法)。

NewClass = SomeMetaClass.__new__('NewClass', (object, ), {})

The __new__ method is something similar to __init__ and gets called prior to __init__ . __new__方法类似于__init__并且在__init__之前被调用。 It will be clear with the following example: 通过以下示例将显而易见:

In [1]: class Foo(object):
   def __new__(cls, *args, **kwargs):
      print 'inside __new__'
      return super(Foo, cls).__new__(cls, *args, **kwargs)

   def __init__(self, *args, **kwargs):
      print 'inside __init__'

In [2]: f = Foo() 
inside __new__ 
inside __init__

Execution sequence when f = Foo() is called is as follows: 调用f = Foo()时的执行顺序如下:

  • Foo.__new__() gets called Foo.__new__()被调用
  • It calls its parent's new method using __super__ 它使用__super__调用其父级的新方法。
  • finally the __new__ method of object is called, and the class is instantiated. 最后调用对象的__new__方法,并实例化该类。
  • Finally the __init__ method of Foo is called. 最后,调用Foo__init__方法。

Check this for more info. 检查以获取更多信息。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM