Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when changing class' __name__ and accessing it from an instance

I'm new in Python and in the Python tags here so I really don't know what is going around. Forgive me if this is a duplicate although I didn't find one.

I ran these commands on my interpreter:

>>> class X():
...     pass
... 
>>> X
<class '__main__.X'>
>>> X.__name__ = "Test"
>>> X
<class '__main__.X'>
>>> y = X()
>>> y
<__main__.X object at 0x7f6971e7a860>   
>>> y.__class__().__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute '__name__'

Can anybody explain me why this Error raises? I was waiting to get "Test" back. Thanks, in advance.

like image 215
JAAAY Avatar asked Jun 24 '26 15:06

JAAAY


1 Answers

You're creating another instance of the class by calling the class constructor again:

y.__class__().__name__ 
#          ^^ 

You need to just refer to the class object i.e. drop the parentheses:

y.__class__.__name__
like image 151
heemayl Avatar answered Jun 27 '26 06:06

heemayl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!