Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

10. Use __slots__ for Better Attributes Control

Sumit Rawal answered on May 13, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • __slots__ python example
  • php slots
  • __slots__ variable in Python

  • 10. Use __slots__ for Better Attributes Control

    0

    As a dynamic language, Python has more flexibility than other languages such as Java or C++. When it comes to OOP, a big advantage is that we can add extra attributes and methods into a Python class at runtime.

    For example, the following code defines a class named Author. We can add an extra attribute age into an instance of this class:

    However, in some cases, allowing the users of a class to add additional attributes at runtime is not a safe choice. Especially when the user has no idea about the implementation of the class. Not to mention that it may invoke out-of-memory issues if a user adds too many extra attributes.

    Therefore, Python provides a special built-in attribute — __slots__ .

    We can add it to a class definition and specify the names of all valid attributes of the class. It works as a whitelist.

    Now, let’s change the previous program a bit:

    Popularity 1/10 Helpfulness 1/10 Language python
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 13 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.