Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
Why is python mangling here

Why does this code fail if there is no cls. before __TEXT

__TEXT = "abcde"

print(__TEXT)
class aaa():
    @classmethod
    def bbb(cls):
        print(__TEXT)

aaa.bbb()

The output is:

abcde
Traceback (most recent call last):
  File "<string>", line 9, in <module>
  File "<string>", line 7, in bbb
NameError: name '_aaa__TEXT' is not defined

If you make __TEXT a class variable and try to reference it without the class prefix as follows:

class aaa():
    __TEXT = "abcde"
    @classmethod
    def bbb(cls):
        print(cls.__TEXT)
        print(__TEXT)

x = aaa()
x.bbb()

You get the same error but it doesn't make sense:

abcde
Traceback (most recent call last):
  File "<string>", line 10, in <module>
  File "<string>", line 7, in bbb
NameError: name '_aaa__TEXT' is not defined
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In PEP 8, they specifically say:

__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo ...).

Notice the selection in bold. In the exact same sentence where they draw attention to mangling's use in naming class attributes, they state that the mangling happens to any __boo inside of the class, which perfectly explains what you are observing.

over 4 years ago · Santiago Trujillo Relatório

0

Not quite sure if that was the error, but you can just make the function require a parameter text, that seems to work just fine. You need to give me more information though so I can try to help.

    __TEXT = "abcde"

    print(__TEXT)
    class aaa():
    @classmethod
    def bbb(self, __TEXT):
       print(__TEXT)

    aaa.bbb(__TEXT)
over 4 years ago · Santiago Trujillo Relatório

0

A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses.

This is also called "name mangling." The interpreter changes the name of the variable in a way that makes it harder to create collisions when the class is extended later.

Reference docs: https://docs.python.org/3/tutorial/classes.html#private-variables

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda