Python Forum

Full Version: Attribute Error received not understood (Please Help)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Community,

I’m having trouble understanding why the following query fails. I’ve run this in the editor a few times but it’s still not clicking conceptually. It returns the following error message “AttributeError: ‘A’ object has no attribute ‘__a’”

Can someone please help me understand?

class A:
    def __init__(self, v):
        self.__a = v + 1
a = A(0)
print(a.__a)
This is due to the double underscore. This is covered under identifiers in the manual. Look for "name mangling".

The name is treated as a private name and is modified. Basically, you shouldn't use double underscores without a good reason. But the data is available under a different name.

class A:
    def __init__(self, v):
        self.__a = v + 1

a = A(0)
print(a._A__a)
Output:
1
(Jun-18-2021, 09:13 PM)crocolicious Wrote: [ -> ]Hello Community,

I’m having trouble understanding why the following query fails. I’ve run this in the editor a few times but it’s still not clicking conceptually. It returns the following error message “AttributeError: ‘A’ object has no attribute ‘__a’”

Can someone please help me understand?

class A:
    def __init__(self, v):
        self.__a = v + 1
a = A(0)
print(a.__a)
Thank you both for your help, this is very helpful!

Croc
(Jun-19-2021, 04:46 AM)buran Wrote: [ -> ]You can find these links useful
The Meaning of Underscores in Python
What is the meaning of single and double underscore before an object name?

Thank you very much Buran. Will read up at both links!

Thanks again,
Croc