문제

파이썬에서는 ''를 사용할 수 있습니다. ' 물체의 사전 항목에 액세스하기 위해. 예를 들어:

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

위의 예에서 'a'객체를 갖는 것은 'foo'메소드에 대한 상위 네임 스페이스 인 'obj'에 대한 참조에서 얻을 수 있습니까? 예를 들어 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_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

Python2.6 동의어 이후 im_self 그리고 im_func ~이다 __self__ 그리고 __func__, 각각. im* 속성은 PY3K로 완전히 사라졌습니다. 따라서 다음으로 변경해야합니다.

>> a.__self__
<__main__.test object at 0xb7b7d9ac>
>> a.__self__.b = 2
>> obj.b
2
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top