[Python-ideas] of properties and metaclasses

Ron Adam rrr at ronadam.com
Tue Jul 24 04:04:44 CEST 2007



Greg Ewing wrote:
> Ron Adam wrote:
> 
>> property foo():
>>      __value__ = value

This should have been __value__ = None.

>>      def __get__():
>>          return __value__
>>      def __set__(value)
>>          __value__ = value


>> The same object in a class might look like...
>>
>> property foo(self):
>>     self.__value__ = None
>>     def __get__(self):
>>         return self.__value__
>>     def __set__(self, value):
>>         self.__value__ = value
> 
> In the first version, how is anything supposed to know that
> the __value__ inside the function is an implicit attribute
> of self rather than a local variable of the function

In the first example self isn't implicit, it's non-existent.  It would work 
more like a generator that yields it value on gets, and receives its value 
on sets.

In the second version self is passed to the functions explicitly so it can 
work in an instance.  But other than that it's the same.  It could also 
keep state between calls, in which case all instances of that class would 
share those values.  (just like instances share class attributes)

   class bar(object):
      property foo(self):
          countgets = 0
          self.__value__ = None
          def __get__()
              countgets += 1
              return countgets, self.__value__
          def __set__(value)
              self.__value__ = value

In this case countgets will be the total gets of all subclasses of bar.

This could be done with a class attribute as well, but that breaks the idea 
of having a single self contained component.  Having self contained 
components is more conducive to a modular design where you can more easily 
reuse parts.

Cheers,
    Ron


> I can't see this flying, for all the reasons that suggestions
> for implicit 'self' in methods get shot down in milliseconds.

I can see that.  I actually like self.  :-)

The feature I recently wanted was a dynamic __contained_in__ attribute to 
go along with self.  But on a wider scale than class's self.  For example 
an object in a list could get a reference to the list object it's in.  (or 
dictionary, function, class, etc.)  And if you moved that object to another 
container, the __contained_in__, attribute would change to reflect that.

The reason I wanted that is it can get around the chicken and egg situation 
of  having to construct windows and frames in tkinter before creating the 
objects that go in them.  I wanted to create the buttons and lables and 
other interior items first and then add them to frames later by appending 
them to a list like frame object.  It could completely do away with the 
need to pass handles around.

But there are places were you really need to construct things in a certain 
order.

Cheers,
    Ron








More information about the Python-ideas mailing list