If Bar used a _metaclass_ attribute that created Bar with type() (and not type._new_()), the subclasses will not inherit that behavior. Then if it can't find any _metaclass_ at all, it will use the Bar's (the first parent) own metaclass (which might be the default type) to create the class object.īe careful here that the _metaclass_ attribute will not be inherited, the metaclass of the parent ( Bar._class_) will be. If Python can't find _metaclass_, it will look for a _metaclass_ at the MODULE level, and try to do the same (but only for classes that don't inherit anything, basically old-style classes). If yes, create in-memory a class object (I said a class object, stay with me here), with the name Foo by using what is in _metaclass_. It will use it to create the object class Foo. Python will look for _metaclass_ in the class definition. You write class Foo(object) first, but the class object Foo is not created If you do so, Python will use the metaclass to create the class Foo. In Python 2, you can add a _metaclass_ attribute when you write a class (see next section for the Python 3 syntax): class Foo(object): Type is the built-in metaclass Python uses, but of course, you can create your You can call it a 'class factory' if you wish. So, a metaclass is just the stuff that creates class objects. Now, what is the _class_ of any _class_ ? > age._class_._class_ You see that by checking the _class_ attribute.Įverything, and I mean everything, is an object in Python. Just the class that creates class objects. Strings objects, and int the class that creates integer objects. Well, I guess it's a matter of consistency with str, the class that creates Now you wonder "why the heck is it written in lowercase, and not Type?" Metaclass Python uses to create all classes behind the scenes. It's because the function type is in fact a metaclass.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |