On Wed, Jan 22, 2020 at 9:04 AM Ethan Furman <et...@stoneleaf.us> wrote:
>
> 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!)
>

Yes, that's exactly what I mean, and exactly why self.__class__ is
used here. If you actually want "Person" even if it's actually a
Martian, you can use __class__.__name__ rather than
self.__class__.__name__ to get that.

ChrisA
_______________________________________________
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/P2AQBDQ4F2YYYSAMDUFKZNNKXFEP3HBU/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to