Pythonでオブジェクトの親名前空間を取得しますか?
-
11-09-2019 - |
質問
Pythonでは、「」を使用することが可能です。オブジェクトの辞書項目にアクセスするため。例えば:
class test( object ) :
def __init__( self ) :
self.b = 1
def foo( self ) :
pass
obj = test()
a = obj.foo
上記の例から、「a」オブジェクトがある場合、そこから「foo」メソッドが割り当てられている親名前空間である「obj」への参照を取得することは可能ですか?たとえば、obj.b を 2 に変更するには?
解決
2.6+(パイソン3を含む)
Pythonの
あなたはバウンドの __self__
プロパティを使用することができますメソッドがバインドされているインスタンスにアクセスするためのの方法。
>> a.__self__
<__main__.test object at 0x782d0>
>> a.__self__.b = 2
>> obj.b
2
Pythonの2.2 +(Pythonの2.xの場合のみ)
またim_self
プロパティを使用することができますが、これは、前方のPython 3との互換性がありません。
>> a.im_self
<__main__.test object at 0x782d0>
他のヒント
バインドされたメソッドでは、次の 3 つの特別な読み取り専用パラメーターを使用できます。
- im_func (バインドされていない) 関数オブジェクトを返します。
- 私自身 関数がバインドされているオブジェクト (クラス インスタンス) を返します。
- im_class のクラスを返します 私自身
テスト中:
class Test(object):
def foo(self):
pass
instance = Test()
instance.foo # <bound method Test.foo of <__main__.Test object at 0x1>>
instance.foo.im_func # <function foo at 0x2>
instance.foo.im_self # <__main__.Test object at 0x1>
instance.foo.im_class # <__main__.Test class at 0x3>
# A few remarks
instance.foo.im_self.__class__ == instance.foo.im_class # True
instance.foo.__name__ == instance.foo.im_func.__name__ # True
instance.foo.__doc__ == instance.foo.im_func.__doc__ # True
# Now, note this:
Test.foo.im_func != Test.foo # unbound method vs function
Test.foo.im_self is None
# Let's play with classmethods
class Extend(Test):
@classmethod
def bar(cls):
pass
extended = Extend()
# Be careful! Because it's a class method, the class is returned, not the instance
extended.bar.im_self # <__main__.Extend class at ...>
ここで注目すべき興味深い点があり、メソッドがどのように呼び出されるかについてのヒントが得られます。
class Hint(object):
def foo(self, *args, **kwargs):
pass
@classmethod
def bar(cls, *args, **kwargs):
pass
instance = Hint()
# this will work with both class methods and instance methods:
for name in ['foo', 'bar']:
method = instance.__getattribute__(name)
# call the method
method.im_func(method.im_self, 1, 2, 3, fruit='banana')
基本的に、 私自身 バインドされたメソッドの属性が変更され、呼び出し時に最初のパラメータとして使用できるようになります。 im_func
im_self
とim_func
ためのpython2.6同義語は、それぞれ__self__
と__func__
、からです。 im*
属性は完全にpy3kになくなっています。あなたはそれを変更する必要があります:
>> a.__self__
<__main__.test object at 0xb7b7d9ac>
>> a.__self__.b = 2
>> obj.b
2
所属していません StackOverflow