Python Forum
Attribute Error received not understood (Please Help) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Attribute Error received not understood (Please Help) (/thread-34022.html)



Attribute Error received not understood (Please Help) - crocolicious - Jun-18-2021

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)



RE: Attribute Error received not understood (Please Help) - bowlofred - Jun-19-2021

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



RE: Attribute Error received not understood (Please Help) - buran - Jun-19-2021

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?


RE: Attribute Error received not understood (Please Help) - crocolicious - Jun-19-2021

(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)



RE: Attribute Error received not understood (Please Help) - crocolicious - Jun-19-2021

Thank you both for your help, this is very helpful!

Croc


RE: Attribute Error received not understood (Please Help) - crocolicious - Jun-19-2021

(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