在python中获取对象的父命名空间?

时间:2009-06-05 05:03:01

标签: python python-datamodel

在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?

3 个答案:

答案 0 :(得分:17)

在绑定方法上,您可以使用三个特殊的只读参数:

  • im_func ,返回(未绑定)函数对象
  • im_self ,返回函数绑定的对象(类实例)
  • im_class ,返回 im_self
  • 的类

围绕测试:

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

时将其用作第一个参数

答案 1 :(得分:14)

Python 2.6+(包括Python 3)

您可以使用__self__ property of a bound method来访问方法绑定的实例。

>> 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>

答案 2 :(得分:7)

因为im_selfim_func的python2.6同义词分别是__self____func__。 py3k中im*属性完全消失了。所以你需要把它改成:

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