Domanda

In Python è possibile utilizzare '' al fine di accedere alle voci del dizionario dell'oggetto. Ad esempio:

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

Da sopra esempio, avere 'un' oggetto, è possibile ottenere da esso riferimento a 'obj' che è uno spazio dei nomi genitore per 'pippo' metodo assegnato? Ad esempio, per cambiare obj.b in 2?

È stato utile?

Soluzione

Python 2.6+ (compreso Python 3)

È possibile utilizzare il __self__ proprietà di un balzo metodo per accedere alla istanza che il metodo è associato.

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

Python 2.2 + (Python 2.x solo)

È anche possibile utilizzare la proprietà im_self, ma questo non è l'ora compatibile con Python 3.

>> a.im_self
<__main__.test object at 0x782d0>

Altri suggerimenti

In metodi bound, è possibile utilizzare tre parametri speciali di sola lettura:

  • im_func che restituisce il (non legato) oggetto funzione
  • im_self , che restituisce l'oggetto della funzione è destinata a (istanza di classe)
  • im_class , che restituisce la classe di im_self

Test in giro:

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

C'è una cosa interessante da notare qui, che ti dà un suggerimento su come i metodi sono chiamati:

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

Fondamentalmente, im_self attributo di un rilegati cambiamenti metodo, per consentire l'utilizzo come primo parametro quando si chiama im_func

in quanto sinonimi python2.6 di im_self e im_func sono rispettivamente __self__ e __func__,. attributi im* sono completamente scomparsi in py3k. così si avrebbe bisogno di cambiarlo in:

>> a.__self__
<__main__.test object at 0xb7b7d9ac>
>> a.__self__.b = 2
>> obj.b
2
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top