Skip to content

Instantly share code, notes, and snippets.

@shomah4a
Created March 16, 2012 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shomah4a/2047983 to your computer and use it in GitHub Desktop.
Save shomah4a/2047983 to your computer and use it in GitHub Desktop.
クラスを調べるときに試したコード
#-*- coding:utf-8 -*-
import traceback
def aaa(cls):
__class__ = cls
def bbb(y):
return super().__init__()
return bbb
def bbb(instance, cls):
__class__ = cls
super().__init__()
def check__class__(f):
print('***', f.__name__, 'defined at line', f.__code__.co_firstlineno)
if '__class__' in f.__code__.co_freevars:
print('***', f.__name__, id(f), 'has __class__')
else:
print('***', f.__name__, id(f), '''doesn't have __class__''')
return f
def get__class__(f):
try:
cls = f(10)
print('aaaaaaaaaaa', cls)
except Exception as e:
print(e)
class Base(object):
@check__class__
def __init__(self):
print('self', self, 'in Base.__init__')
print('aaaa')
super().__init__()
@check__class__
def test(self, x):
print('self', self)
print('__class__', __class__)
print('basetest', x)
class Derived(Base):
@check__class__
def __init__(self):
print('self', self, 'in Derived.__init__')
x = 10
print(locals())
print('__class__:', __class__)
print('bbbb')
super().__init__()
@check__class__
def somefunc(self, y):
pass
@check__class__
def somefunc2(self, y):
super(Derived, self).test(10)
@get__class__
def somehaveclass(self):
if 0:
super()
return __class__
@check__class__
def outertest(self, x):
print('derivedtest', x)
super().test(x)
Derived.test = outertest
Derived.aaa = aaa(Base)
Derived().aaa()
if __name__ == '__main__':
# OK
print('---------- クラス定義と一緒に定義した普通のメソッド ----------')
d = Derived()
check__class__(Derived.__init__)
print('---------- クラスに後から追加した関数をメソッドとして呼び出す ----------')
try:
# __class__ がない
d.test(10)
except SystemError as e:
print('!!!!!!!!! エラーでたー !!!!!!!')
traceback.print_exc()
print('---------- type() を使ってクラスを作ってみる ----------')
SomeTest = type('SomeTest', (Base,), {'test': outertest})
check__class__(SomeTest.test)
b = SomeTest()
try:
b.test(1)
except SystemError as e:
print('!!!!!!!!! エラーでたー !!!!!!!')
traceback.print_exc()
try:
Derived.__init__('aaaa')
except Exception as e:
print(e)
def make_class():
def __init__(self):
super().__init__()
def somefunc(self):
print('test')
__class__ = type('classname', (object,), locals())
return __class__
C = make_class()
a = C()
a.somefunc()
class Base(object):
def __init__(self):
pass
def test(self, x):
print('basetest', x)
class Derived(Base):
def __init__(self):
super().__init__()
def outertest(self, x):
print('derivedtest', x)
super().test(x)
Derived.test = outertest
a = Derived()
a.test(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment