1

I'm a beginner in learning Python and have a question in class attribute. If I define a simple class as followings:

class class_test:
    def __init__(self, name):
        self.name = name

I create a class_test object a with an initial value

a = class_test('John')

Now I would change object's attribute value, but I specify the attribute with a typo.

a.naem = 'Mary'

This creates a new attribute in object instead of generating attribute error. I know this may not be a good way to change object attributes. I am just curious that this kind of error can be detected in compile time in other languages such as C++. In Python, class and object can add new attributes after they are created. Is there options to disallow this behavior? Is there anyway to generate attribute error instead of creating new attributes for typo?

huangjj
  • 11
  • 2
  • If you are using any modern code text editor, you can enable tools like [pylance](https://github.com/microsoft/pylance-release), that can detect such things pretty much like a static-typed language, with the only difference that you can choose to ignore the warning. – Rodrigo Rodrigues Oct 05 '22 at 03:18

1 Answers1

3

One option is to use __slots__ and write the attribute names allowed for instances:

class class_test:

    __slots__ = ('name',)

    def __init__(self, name):
        self.name = name

The general principle is to open up additional space for the C structure of the instance, and leave the data descriptors corresponding to each attribute in the class. They can read and write values in the structure according to the offset, and remove the __dict__ attribute to disable the dynamic attribute.

Test:

>>> a = class_test('John')
>>> a.naem = 'Mary'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'class_test' object has no attribute 'naem'

For more details, please refer to: Usage of __slots__?

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31