Inserting class namespace into method scope

Emile van Sebille emile at fenx.com
Sat Nov 20 18:12:18 CET 2010


On 11/20/2010 6:59 AM Steven D'Aprano said...
> I find myself having need of a class where the class scope is included in
> the scope of methods in the class. A simple example from Python 3.1:
>
> x = "outside"
>
> class Magic:
>      x = "inside"
>      def method(self):
>          return x
>
>
> I would like Magic().method() to return "inside" rather than "outside".
>
> Now, I understand why this is not Python's usual behaviour, and I agree
> with those reasons -- this is NOT a complaint that Python's normal
> behaviour is to exclude the class namespace from the method's scope.
>
> I also understand that the usual way of getting this would be to return
> self.x or self.__class__.x from method, instead of x. Again, normally I
> would do this.
>
> But in this specific case I have reasons for wanting to avoid both of the
> normal behaviours. Do not judge me, please accept that I have a good
> reason for wanting this, or at least allow me to shoot myself in the foot
> this way *wink*. In Python 3, is there some way to get this unusual
> behaviour?
>

As it's easy to return self.x but you're restricting that option, what 
kind of change options must you work within?

Emile






More information about the Python-list mailing list