gri*_*yvp 9 python python-datamodel
在python中,可以使用'.' 为了访问对象的字典项.例如:
class test( object ) :
def __init__( self ) :
self.b = 1
def foo( self ) :
pass
obj = test()
a = obj.foo
Run Code Online (Sandbox Code Playgroud)
从上面的示例中,拥有'a'对象,是否有可能从它引用'obj',它是'foo'方法分配的父命名空间?例如,将obj.b更改为2?
Nic*_*zet 17
在绑定方法上,您可以使用三个特殊的只读参数:
测试周围:
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 ...>
Run Code Online (Sandbox Code Playgroud)
这里有一个有趣的事情需要注意,它提供了如何调用方法的提示:
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')
Run Code Online (Sandbox Code Playgroud)
基本上,绑定方法的im_self属性会发生变化,以允许在调用im_func时将其用作第一个参数
Mil*_*les 14
您可以使用__self__绑定方法的属性来访问该方法绑定的实例.
>> a.__self__
<__main__.test object at 0x782d0>
>> a.__self__.b = 2
>> obj.b
2
Run Code Online (Sandbox Code Playgroud)
您也可以使用该im_self属性,但这与Python 3不兼容.
>> a.im_self
<__main__.test object at 0x782d0>
Run Code Online (Sandbox Code Playgroud)
因为python2.6的同义词im_self和im_func是__self__和__func__分别.im*属性在py3k中完全消失了.所以你需要将它改为:
>> a.__self__
<__main__.test object at 0xb7b7d9ac>
>> a.__self__.b = 2
>> obj.b
2
Run Code Online (Sandbox Code Playgroud)