>>> class a:
... hoge=2
... def hage(self, x):
... self.hoge=x
... def fuga(self, y):
... return self.hoge
...
>>> vars()['a'].__dict__
{'__module__': '__main__', 'fuga': <function fuga at 0x00930DF0>, 'hage': <funct
ion hage at 0x00930CF0>, '__doc__': None, 'hoge': 2}
>>> vars()['a'].hoge
2
>>> vars()['a'].__dict__['hoge']
2
>>> i=vars()['a']
>>> i.fuga(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method fuga() must be called with a instance as first argumen
t (got int instance instead)
>>> i=vars()['a']()
>>> i.fuga(0)
2
>>> i=vars()['a']
>>> j=i()
>>> j.hoge
2
>>> j.fuga(0)
2
>>> j.__dict__
{}
生成されたインスタンスからメンバやメソッド情報を得るにはどうすればよいですか
j.__class__.__dict__
dir
inspect.getmembers
__class__.__dict__ にある関数はインスタンスと関連付けされてない点に注意。
a.__dict__['fuga'](j, 0) # 引数 self にあたる部分を自分で渡す必要がある
恐らくやりたいことは、dir(instance) で調べて、getattr(j, 'fuga')(0)
dir だと余計なメンバも混ざってくる。
__class__.__dict__だと親クラスの情報が含まれない。
メソッドのみを調べる場合は、
[name for name,boundmethod in inspect.getmembers(instance, inspect.ismethod)]
メンバを含める場合は第二引数を省略。
[name for name,boundmethod in inspect.getmembers(instance) if not name.startswith('__') and not name.endswith('__')]
>>> j.__class__.__dict__['hoge']
2
>>> j.__class__.__dict__['fuga'](0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fuga() takes exactly 2 arguments (1 given)
>>> j.__class__.__dict__['fuga'](j, 0)
2
>>> j.hoge=9
>>> j.__class__.__dict__['fuga'](j, 0)
9
できました
ありがとうございました
もっと勉強してみます
>>> class b(a):
... hige=3
... def fuga(self, x):
... return self.hoge + x
>>> class a:
... hoge=2
... def hage(self, x):
... self.hoge=x
>>> aa=a()
>>> bb=b()
>>> aa.__class__.__dict__
{'__module__': '__main__', '__doc__': None, 'hage': <function hage at 0x00930D70>, 'hoge': 2}
>>> bb.__class__.__dict__
{'__module__': '__main__', 'fuga': <function fuga at 0x00930D30>, 'hige': 3, '__doc__': None}
>>> dir(aa)
['__doc__', '__module__', 'hage', 'hoge']
>>> dir(bb)
['__doc__', '__module__', 'fuga', 'hage', 'hige', 'hoge']
>>> import inspect
>>> inspect.getmembers(aa)
[('__doc__', None), ('__module__', '__main__'), ('hage', <bound method a.hage of <__main__.a instance at 0x00934738>>), ('hoge', 2)]
>>> inspect.getmembers(bb)
[('__doc__', None), ('__module__', '__main__'), ('fuga', <bound method b.fuga of <__main__.b instance at 0x009347B0>>), ('hage', <bound method b.hage of <__main__.b instance at 0x009347B0>>), ('hige', 3), ('hoge', 2)]
>>> [name for name,boundmethod in inspect.getmembers(aa, inspect.ismethod)]
['hage']
>>> [name for name,boundmethod in inspect.getmembers(bb, inspect.ismethod)]
['fuga', 'hage']
>>> [name for name,boundmethod in inspect.getmembers(aa) if not name.startswith('__') and not name.endswith('__')]
['hage', 'hoge']
>>> [name for name,boundmethod in inspect.getmembers(bb) if not name.startswith('__') and not name.endswith('__')]
['fuga', 'hage', 'hige', 'hoge']