1

I wanted to make a similar feature to ECMAScript 5 "frozen" object where you can't change anything on it.

Did this:

class Fixed(object):
        frzn = 'I AM AWESOME'
        def holdset(_,val):
                _.frzn = _.frzn
                print "frozen is frozen not setting to ", val
        frozen = property(fset=holdset)

        @classmethod
        def __setattr__(self, name, val):
                if name=="frozen":
                        print "You can't unfreeze the frozen"
                else:   
                        self.name = val

dd = Fixed()
dd.frozen = 12312312
dd.frozen = 'AA'
Fixed.frozen = {}
print dd.frozen
print Fixed.frozen

Which gives

You can't unfreeze the frozen You can't unfreeze the frozen {} {}

The first two assignments fail, when they reference the attribute as an instance member. The third assignment succeeds, when the attribute is referenced as a class member.

I don't understand why.

How can I make

Fixed.frozen = {}

Fail in the same way the other assignments did? And why doesn't it?

1 Answer 1

3

You need to override __setattr__ of the Metaclass. Metaclass is a class that creates a class (Similar to instance created by a class), So, to override things related to class object you need to modify the special methods on the Metaclass.

class Meta(type):

    def __setattr__(self, attr, val):
        if attr == "frozen":
            print "You can't unfreeze the frozen"
        else:   
            cls.name = val

class Fixed(object):
        __metaclass__ = Meta
        ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.