Getting object39s parent namespace in python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

In python it s possible to use . in order to access object s dictionary items. For example:

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

From above example, having a object, is it possible to get from it reference to obj that is a parent namespace for foo method assigned? For example, to change obj.b into 2?

Answers

Python 2.6+ (including Python 3)

https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy

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

Python 2.2+ (Python 2.x only)

You can also use the im_self property, but this is not forward compatible with Python 3.

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

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/954340/getting-objects-parent-namespace-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils