在 python 中,可以使用 '.' 来访问对象的字典项。例如:

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

从上面的示例中,有“a”对象,是否可以从它获取对“obj”的引用,“obj”是分配的“foo”方法的父命名空间?比如把obj.b改成2?

有帮助吗?

解决方案

的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_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_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归因
不隶属于 StackOverflow
scroll top