1

I have such code

class Toy(): def __init__(self, color, age): self.color = color self.age = age self.my_dict = { 'name':'Yoyo', 'has_pets': False, } def __setattr__(self, key, value): if key == 'color' or key == 'age' or key == 'my_dict': # want to make like this 'self.__dict__.keys()' object.__setattr__(self, key, value) else: print('Wrong value') 

Main idea is to disallow users to add new custom attributes to a class. Is there is way to tell __setattr__ not to check keys if it called from __init__? If so then I could use self.__dict__.keys() in __setattr__ and don't check every key by name

2 Answers 2

2

Use the __slots__ class attribute:

class Toy: __slots__ = ('color', 'age', 'my_dict') def __init__(self, color, age): self.color = color self.age = age self.my_dict = { 'name':'Yoyo', 'has_pets': False, } 

Any attempt to assign to an attribute other than color, age, or my_dict will result in an AttributeError.

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

Comments

0

Didn't found better than this

class Toy: _keys = ["color", "age", "my_dict"] def __init__(self, color, age): self.color = color self.age = age self.my_dict = { 'name':'Yoyo', 'has_pets': False, } def __setattr__(self, key, value): if key in self._keys: object.__setattr__(self, key, value) else: print('Wrong value') 

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.