簡體   English   中英

在python中獲取對象的父命名空間?

[英]Getting object's parent namespace in python?

在python中,可以使用'。' 為了訪問對象的字典項。 例如:

class test( object ) :
  def __init__( self ) :
    self.b = 1
  def foo( self ) :
    pass
obj = test()
a = obj.foo

從上面的例子中,擁有'a'對象,是否有可能從它引用'obj',它是'foo'方法分配的父命名空間? 例如,將obj.b更改為2?

在綁定方法上,您可以使用三個特殊的只讀參數:

  • im_func返回(未綁定)函數對象
  • im_self返回函數綁定的對象(類實例)
  • 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_self屬性會發生變化,允許在調用im_func時將其用作第一個參數

Python 2.6+(包括Python 3)

您可以使用綁定方法__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>

因為im_selfim_func python2.6同義詞分別是__self____func__ im*屬性在py3k中完全消失了。 所以你需要將它改為:

>> a.__self__
<__main__.test object at 0xb7b7d9ac>
>> a.__self__.b = 2
>> obj.b
2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM