0

How to prevent python object from adding variables

class baseClass1:
    count=0;
    def displayCount(self):
        print "Total Employee %d" % baseClass1.count;


base = baseClass1();
base.type = "class"; #  i want to throw an error here
5
  • What purpose does this serve? Commented Dec 17, 2014 at 7:11
  • It is (sort of) possible, but why do you feel you need to do it? Commented Dec 17, 2014 at 7:13
  • Unrelated to your problem, but you don't need to use semicolons at the end of the line. Commented Dec 17, 2014 at 7:17
  • @viraptor Semi-colons are, however, an optional part of the language. Commented Dec 17, 2014 at 8:10
  • @Shule I was just pointing out to the obvious python beginner that it's not the common style. Parentheses are also valid and optional, but nobody writes if ((((((((expression)))))))): Commented Dec 17, 2014 at 9:27

2 Answers 2

5

You can use __slots__ - have a look at the documentation.

class baseClass1(object):
    __slots__ = ['count']

The exception thrown on unknown attribute will be AttributeError.

You have to make sure you use the new-style classes for this to work (explicitly inherit from object)

Sign up to request clarification or add additional context in comments.

Comments

1

You can override the class' __setattr__ and do whatever checks you want. In this example I'm not allowing and setting of members that were not defined in the constructor. It will save you from manually maintaining that list.

class baseClass1:
        # allowed field names
        _allowed = set()

        def __init__(self): 
            # init stuff
            self.count=0
            self.bar = 3

            # now we "freeze the object" - no more setattrs allowed
            self._frozen = True

        def displayCount(self):

            print "Total Employee %d" % baseClass1.count;



        def __setattr__(self, name, value):

            # after the object is "frozen" we only allow setting on allowed field
            if  getattr(self, '_frozen', False) and name not in self.__class__._allowed:
                raise RuntimeError("Value %s not allowed" % name)
            else:
                # we add the field name to the allowed fields
                self.__class__._allowed.add(name)
                self.__dict__[name] = value



    base = baseClass1();
    base.count = 3 #won't raise
    base.bar = 2 #won't raise
    base.type = "class"; # throws

6 Comments

your solution will throw exception when we are trying to change the count value. base.count =2 # also throws
@beginner of course it will. you can simply add a check that we're not changing count. BTW count should be a member and not a class member. I'll modify my code.
if we have more that ten variables are we going to put excuse for all those variables. Is there any other solution . Any one clarification will it work for if any static variables present
@beginner let's suppose that you want it to support what's set by the constructor and nothing else - I'll modify my answer here. Re static members - what exactly do you want to do? setattr is for object members, not class members.
static members that is clear for me now. Thanks for reply. We are including this if name !='count' but if we are having more than ten variables we cant use this right ? i am asking is there any solution to take of that also ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.