Static properties
Shalabh Chaturvedi
shalabh at cafepy.com
Thu Aug 26 20:02:32 EDT 2004
Per Erik Stendahl wrote:
> Hello everyone,
>
> Is it possible to define "static properties" in a class?
Yes and no, depending on what exactly you want :)
> Example:
> I have a class, Path, that wraps a lot of os.* and os.path.* functions
> (and others), so I can write things like this:
>
> x = Path('/usr/local/some/file')
> if x.IsFile:
> contents = x.Read()
> ...
>
> Now, I would like to wrap os.getcwd(). I can do it like this:
>
> class Path:
> def CurrentDirectory():
> return os.getcwd()
> CurrentDirectory = staticmethod(CurrentDirectory)
>
> pwd = Path.CurrentDirectory()
>
> Question: Can I make CurrentDirectory a property? Just adding
> CurrentDirectory = property(CurrentDirectory) after the staticmethod
> line didn't work, unsurprisingly. :-)
If you use raw descriptors and not properties, you can make computed
class attributes:
class CurrentDirectoryDesc(object):
def __get__(self, obj, cls=None):
return os.getcwd()
class Path(object):
CurrentDirectory = CurrentDirectoryDesc()
print Path.CurrentDirectory
print Path().CurrentDirectory
Note that:
- the classes are derived from object
- you cannot make a settable class attribute this way (you have to use a
metaclass for that)
- if you subsequently assign Path.CurrentDirectory, you will overwrite
the descriptor
HTH,
Shalabh
More information about the Python-list
mailing list