Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

メタクラスプロトコル

781 views

Published on

  • Be the first to comment

  • Be the first to like this

メタクラスプロトコル

  1. 1. メタクラスプロトコル aodag
  2. 2. クラスとオブジェクト >>> class A(object): ... pass ... >>> A <class '__main__.A'> >>> a = A() >>> AA = A >>> aa = AA() >>> a <__main__.A object at 0x922b0> >>> aa <__main__.A object at 0x92210>
  3. 3. >>> a.__class__ <class '__main__.A'> >>> a.__class__ is A True >>> aa.__class__ is A True
  4. 4. クラスとタイプ >>> aa.__class__ is A True >>> A.__class__ <type 'type'>
  5. 5. typeコンストラクタで動的にクラス定義 >>> X = type('X', (A,), {}) >>> X <class '__main__.X'> >>> x = X() >>> isinstance(x, A) True >>> isinstance(x, X) True
  6. 6. クラスとメタクラス >>> class AType(type): ... def __init__(cls, name, parents, dct): ... super(AType, cls).__init__(name, parents, dct) ... print '%s defined' % name ... >>> class AAA(object): ... __metaclass__ = AType ... AAA defined
  7. 7. メタクラス応用 def trace(func): def wrap(*args, **kwargs): print args, kwargs return func(*args, **kwargs) return wrap class Traceable(type): def __init__(cls, name, parents, dct): super(Traceable, cls).__init__(name, parents, dct) for k, v in [(k, trace(v)) for k, v in dct.iteritems() if callable (v) and not k.startswith('_')]: setattr(cls, k, v)
  8. 8. 使ってみる class Hello(object): __metaclass__ = Traceable def greedy(self, name): print "Hello, %s" % name h = Hello() h.greedy('aodag')

×