标签云

微信群

扫码加入我们

WeChat QR Code


"You won't be able to recreate something like type purely in Python, but Python cheats a little" is not true.

2018年10月22日15分29秒

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

2018年10月22日15分29秒

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

2018年10月21日15分29秒

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/…

2018年10月22日15分29秒

<<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?

2018年10月21日15分29秒

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

2018年10月21日15分29秒

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).

2018年10月21日15分29秒

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

2018年10月21日15分29秒

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.

2018年10月21日15分29秒

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

2018年10月22日15分29秒