Static class methods
Alex Shindich
alex at shindich.com
Sun Mar 4 20:47:46 EST 2001
----- Original Message -----
From: "Sven Peters" <svpeters at t-online.de>
Newsgroups: comp.lang.python
Sent: Sunday, March 04, 2001 4:06 PM
Subject: Re: Static class methods
> Chris Armstrong wrote:
>
> > I have trouble believing that something like this is really needed.
> > Could you give a real-world example?
> Factoty methods, for getting objects created earlier and no longer needed,
> yet expensive to create e.g. database connection pooling.
> Sure, you can place this elsewhere(module level or other objects).
> Interresting:
> You CAN have class methods:
> def bert:
> print "Bert"
> class.method = bert
> class.method()
> "Bert"
>
> ... but no language support to create them as easy as instance methods
>
> --
> Sven Peters
Amen! Most factories are implemented as module-level functions today. This
decouples classes from factories. Sometimes this behavior is desired.
Sometimes a factory method pattern is more appropriate. As of today, Python
doesn't allow for factory methods.
Another need for static methods comes from a very basic OOP principle --
encapsulation. Sometimes a private class-level utility function is needed.
The only way to have a function like that today is to have a private
instance method. This is damn ugly!
Regards,
Alex Shindich
visit http://www.shindich.com/sources/
P.S. The code snippet above won't work, because an operation of adding a
function attribute to any instance creates an attribute of type instance
method:
>>> def bert ():
print "Bert"
>>> class Foo: pass
>>> Foo.method = bert
>>> Foo.method ()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in ?
Foo.method ()
TypeError: unbound method bert() must be called with instance as first
argument
>>>
More information about the Python-list
mailing list