I got stuck when I try to figure out the following codes
:
def with_metaclass(meta, base=object):
print("[2]")
return meta("NewBase", (base,), {})
class BaseForm(object):
def __init__(self, fields, prefix=''):
print(self.__class__)
def say(self):
print("BaseForm")
class FormMeta(type):
def __init__(cls, name, bases, attrs):
print("[3]: {!r}, {!r}, {!r}, {!r}, {!r}".format(cls, name, type(cls), bases, attrs))
type.__init__(cls, name, bases, attrs)
def __call__(cls, *args, **kwargs):
print("[4]: {!r}, {!r}".format(cls, type(cls)))
return type.__call__(cls, *args, **kwargs)
print("[1]")
class Form(with_metaclass(FormMeta, BaseForm)):
print("[5]")
def __init__(self):
NewBase.__init__(self)
print("[6]: {!r}, {!r}".format(self, type(self)))
# confused position
print(Form.__bases__)
# Form is based on NewBase, however, there is no NewBase
print(dir())
here is the code output:
[1]
[2]
[3]: <class '__main__.NewBase'>, 'NewBase', <class '__main__.FormMeta'>, (<class '__main__.BaseForm'>,), {}
[5]
[3]: <class '__main__.Form'>, 'Form', <class '__main__.FormMeta'>, (<class '__main__.NewBase'>,), {'__module__': '__main__', '__qualname__': 'Form', '__init__': <function Form.__init__ at 0x7f6ad4d76f28>}
(<class '__main__.NewBase'>,)
['BaseForm', 'Form', 'FormMeta', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'with_metaclass']
Just like what I commented out, Form
is base on NewBase
, however, there is not a NewBase
class in the main module. A class its base class is not accessible, is an error? But interesting, Form
can still call the method, which comes from the parent of its parent.