On 01/21/2020 11:25 AM, Chris Angelico wrote:

I'm not sure how this compares to what nameof(Person) should return,
but the above idiom (or something like it) is very common in Python,
as it allows repr to acknowledge a subclass. If you create "class
Martian(Person): pass", then a Martian's repr will say "Martian". On
the other hand, if you actually want "the name of the surrounding
class", then that can be spelled __class__.__name__, and that will
always be Person even if it's been subclassed. Not nearly as common,
but available if you need it.

I'm not sure what you mean, but:

--> class Person:
...     def __init__(self, name):
...         self.name = name
...     def __repr__(self):
...         return '%s(name=%r)' % (self.__class__.__name__, self.name)
...

--> class Martian(Person):
...     pass
...

--> p = Person('Ethan')
--> m = Martian('Allen')

--> p
Person(name='Ethan')

--> m
Martian(name='Allen')

(Same results with f-strings.  Whew!)

--
~Ethan~
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/EX4AFMICCTBUCHUKQ2HYCPQDL2T236BG/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to