Static class properties (read-only)

Alex Martelli aleax at aleax.it
Thu Aug 7 14:23:26 EDT 2003


Greg Brunet wrote:

> In puzzling over classes, I'm wondering if classes can have read-only
> static properties?  I certainly seem to be able to do create static
> properties like this:
> 
> class C(object):
>     count = 0
> 
>     def __init__(self,s):
>         C.count += 1
>         self.Name = s
> 
>     def __del__(self):
>         C.count -= 1
> 
> and C.count should have a count of the number of its instances that have
> been created.  However, someone could set the value directly.  I know
> that using get/set methods, I can make a read-only property at the
> object/instance level.  Can this be done at the class level?  Thanks,

Yes, you can make a class have a read-only property, but you can do this
only by using a custom metaclass.  Once you do make it read-only, of
course, nobody can set it, including methods such as __init__ & __del__!-)


Alex





More information about the Python-list mailing list