_Prevent_ dynamic attribute addition?

Mark McEahern marklists at mceahern.com
Fri Aug 30 13:44:50 EDT 2002


> Is there a way to make a class 'non-modifiable', or am I just not
> understanding something here?

Use slots:

#! /usr/bin/env python

class A(object):

    __slots__ = ['number_of_monkeys', 'smell']

class B(A):

    pass

a = A()
b = B()

attribs = ['number_of_monkeys', 'smell']

for attr in attribs:
    for obj in (a, b):
        inst = obj
        cls = type(inst)
        print "%s: hasattr(%s, %s) --> %s" % \
              ("instance", inst.__class__.__name__, attr, hasattr(inst,
attr))
        print "%s: hasattr(%s, %s) --> %s" % \
              ("class", inst.__class__.__name__, attr, hasattr(cls, attr))

-





More information about the Python-list mailing list