• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
メタクラスプロトコル
 

メタクラスプロトコル

on

  • 624 views

 

Statistics

Views

Total Views
624
Views on SlideShare
623
Embed Views
1

Actions

Likes
0
Downloads
0
Comments
0

1 Embed 1

http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    メタクラスプロトコル メタクラスプロトコル Presentation Transcript

    • メタクラスプロトコル aodag
    • クラスとオブジェクト >>> 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>
    • >>> a.__class__ <class '__main__.A'> >>> a.__class__ is A True >>> aa.__class__ is A True
    • クラスとタイプ >>> aa.__class__ is A True >>> A.__class__ <type 'type'>
    • typeコンストラクタで動的にクラス定義 >>> X = type('X', (A,), {}) >>> X <class '__main__.X'> >>> x = X() >>> isinstance(x, A) True >>> isinstance(x, X) True
    • クラスとメタクラス >>> 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
    • メタクラス応用 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)
    • 使ってみる class Hello(object): __metaclass__ = Traceable def greedy(self, name): print "Hello, %s" % name h = Hello() h.greedy('aodag')