[Python] How to face name mangling with two non-nested public classes with private attributes

Discussão em 'Python' iniciado por Stack, Maio 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have two public classes in Python. They are not nested. They have some private attributes and the second class has an object whose type is the first class. I need to access to the private attributes of the object I created inside the second class.

    I'm not an expert in name mangling but I have read this example.

    I have understood what the problem is, but I don't know how to solve it in my case, since I have one private attribute which is a instance of a public class with some private attributes that need to be accessed from other public class.

    Let's clarify the exact problem with an example:

    class First:

    def __init__(self) -> None:
    self.__size: ...

    def __len__(self) -> int:
    return self.__size


    class Second:

    def __init__(self, first: First) -> None:
    self.__first = first
    self.__size = __first.__size

    def __len__(self) -> int:
    return self.__size


    When I run my tests I obtain some errors:

    self.__size: = first._Second__first
    ^^^^^^^^^^^^^^^^^^^^^
    AttributeError: 'First' object has no attribute '_Second__first'

    Continue reading...

Compartilhe esta Página