标签云

微信群

扫码加入我们

WeChat QR Code

蟒蛇中的元类是什么?

What are metaclasses and what do we use them for?


class A(type):pass<NEWLINE>class B(type,metaclass=A):pass<NEWLINE>b.__class__ = b

2019年04月25日15分24秒

ppperry he obviously meant you can't recreate type without using type itself as a metaclass. Which is fair enough to say.

2019年04月25日15分24秒

Shouldn't unregister()be called by instance of Example class ?

2019年04月25日15分24秒

It appears that in Django models.Model it does not use __metaclass__ but rather class Model(metaclass=ModelBase): to reference a ModelBase class which then does the aforementioned metaclass magic. Great post! Here's the Django source: github.com/django/django/blob/master/django/db/models/…

2019年04月25日15分24秒

<<Be careful here that the __metaclass__ attribute will not be inherited, the metaclass of the parent (Bar.__class__) will be. If Bar used a __metaclass__ attribute that created Bar with type() (and not type.__new__()), the subclasses will not inherit that behavior.>> -- Could you/someone please explain a bit deeper this passage?

2019年04月25日15分24秒

MaxGoodridge That's the Python 3 syntax for metaclasses. See Python 3.6 Data model VS Python 2.7 Data model

2019年04月25日15分24秒

It's a community wiki answer (so, those who commented with corrections/improvements might consider editing their comments into the answer, if they're sure they are correct).

2019年04月25日15分24秒

Which parts of this answer is about python2 and which about pythono3?

2019年04月25日15分24秒

Isn't the use of meta classes adding new properties and methods to a class and not an instance? As far as i understood it the meta class alters the class itself and as a result the instances can be constructed differently by the altered class. Could be a bit misleading to people who try to get the nature of a meta class. Having useful methods on instances can be achieved by normal inherence. The reference to Django code as an example is good, though.

2019年04月25日15分24秒

Thanks for the example.Why did you find this easier than inheriting from MyBase, whose __init__(self) says type(self)._order = MyBase.counter; MyBase.counter += 1 ?

2019年04月25日15分24秒

I wanted the classes themselves, not their instances, to be numbered.

2019年04月25日15分24秒

Right, duh. Thanks. My code would reset MyType's attribute on every instantiation, and would never set the attribute if an instance of MyType was never created.Oops.(And a class property could also work, but unlike the metaclass it offers no obvious place to store the counter.)

2019年04月25日15分24秒

In the metaclass example I get NameError: name 'ValidateType' is not defined. Any suggestions how to best fix this? I'm using python 2

2019年04月25日15分24秒