PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 25, 2022

[FIXED] Why is python mangling here

 November 25, 2022     class, double-underscore, module, python, variables     No comments   

Issue

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

Solution

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.



Answered By - Kraigolas
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing