Skip to content

Instantly share code, notes, and snippets.

@FGtatsuro
Created July 9, 2018 13:42
Show Gist options
  • Save FGtatsuro/0307f5c98b0fefbe868d3c83edbcf280 to your computer and use it in GitHub Desktop.
Save FGtatsuro/0307f5c98b0fefbe868d3c83edbcf280 to your computer and use it in GitHub Desktop.
メタクラスの__new__と__prepare__
# FYI: https://docs.python.jp/3/reference/datamodel.html#metaclass-example
import collections
class OrderedClass(type):
@classmethod
def __prepare__(metacls, clsname, bases, **kwds):
# metacls: メタクラスに指定したtype
# classname: メタクラスを適用したクラスの名前
# bases: 継承したクラスのtypeを格納したtuple
# kwds: クラス定義時にinheritance部(A(...))で与えた名前付き引数を含む辞書
# https://docs.python.jp/3/reference/compound_stmts.html#class-definitions
print(f'prepare:{metacls}')
print(f'prepare:{clsname}')
print(f'prepare:{bases}')
print(f'prepare:{kwds}')
d = collections.OrderedDict()
d['hoge'] = 'piyo'
return d
def __new__(metacls, clsname, bases, namespace, **kwds):
# namespace: メタクラスを適用したクラスの名前空間
# https://docs.python.jp/3/reference/datamodel.html#preparing-the-class-namespace
print(f'new:{metacls}')
print(f'new:{clsname}')
print(f'new:{bases}')
print(f'new:{namespace}')
print(f'new:{kwds}')
result = type.__new__(metacls, clsname, bases, dict(namespace))
result.members = tuple(namespace)
return result
class B:
pass
class A(B, metaclass=OrderedClass, a='test'):
def one(self): pass
def two(self): pass
def three(self): pass
def four(self): pass
a = A()
print(a.members)
print(f'classdict:{A.__dict__}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment