Is classless worth consideration

Yermat loic at fejoz.net
Thu Apr 29 03:10:42 EDT 2004


Michael wrote:
> 
>> It's just occured to me that backing into that particular
>> issue might work: use class methods and never bother
>> with instantiating the classes at all. I'm not sure what
>> we'd lose. (possibly descriptors?)
>>
> You can already use:
> 
> class test:
>     x = 1
> 
> t = test
> print t.x
> 
> 
> Is there any way to to call a class method without making an instance of 
> that class? To me that would be useful because you could mimic modules 
> without having to create a sepperate file. Or is there already a way to 
> do that?
> 

this way ? ! ?

 >>> class Test(object):
...     x = 1
...     def incX(cls, inc):
...             cls.x += inc
...     incX = classmethod(incX)
...
 >>>
 >>>
 >>> t = Test
 >>> t.x
1
 >>> t.incX(2)
 >>> t.x
3

But is it really usefull ? If you really want something per instance 
look at the following code...

 >>> def attach(inst, fct, attrName):
...     setattr(inst, attrName, fct.__get__(inst, inst.__class__))
...
 >>>
 >>> class Test(object):
...     pass
...
 >>>
 >>> t = Test()
 >>> t.x = 2
 >>>
 >>> def incX(self, inc):
...     self.x += inc
...
 >>>
 >>> attach(t, incX, 'incX')
 >>>
 >>> t.x
2
 >>> t.incX(3)
 >>> t.x
5
 >>>
 >>> t1 = Test()
 >>> hasattr(t1, 'x')
False
 >>> hasattr(t1, 'incX')
False




More information about the Python-list mailing list