Skip to content

Instantly share code, notes, and snippets.

@shomah4a
Last active August 29, 2015 14:17
Show Gist options
  • Save shomah4a/5b56a436bd5a42f69e9d to your computer and use it in GitHub Desktop.
Save shomah4a/5b56a436bd5a42f69e9d to your computer and use it in GitHub Desktop.
昨日のインターフェイス的ななにか
#-*- coding:utf-8 -*-
def not_builtin_name(n):
return not n.startswith('__') and not n.endswith('__')
def itermethods(cls):
names = set()
for c in cls.mro():
for n in filter(not_builtin_name, dir(c)):
if n in names:
continue
yield n
names.add(n)
class InterfaceMeta(type):
u''' インターフェイス的なアレを実現するためのもの '''
def __instancecheck__(cls, obj):
for name in itermethodnames(cls):
if not hasattr(obj, name):
return False
return True
class Interface(object):
u''' インターフェイスの基底クラス '''
__metaclass__ = InterfaceMeta
class IHogeable(Interface):
u''' hoge できるというインターフェイス定義 '''
def hoge(self):
pass
class Hogeable(object):
u''' hoge できるやつ '''
def hoge(self):
pass
class DerivedHogeable(Hogeable):
u''' 継承してみる '''
def piyo(self):
pass
class Fugaable(object):
u''' hoge できないやつ '''
def fuga(self):
pass
hogeable = Hogeable()
dhogeable = DerivedHogeable()
fugaable = Fugaable()
print isinstance(hogeable, IHogeable) #=> True
print isinstance(dhogeable, IHogeable) #=> True
print isinstance(fugaable, IHogeable) #=> False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment