[Tutor] what's your name? (to a class)
Dominik George
nik at naturalnet.de
Thu Jan 2 11:18:22 CET 2014
Hi,
> Am I missing something or don't classes know how they're called
> (unlike funcs, which have a __name__ attribute, very practicle)? Is
> there a way to get it otherwise?
The class has it, the instance doesn't. That said, you are looking for self.__class__.__name__ ...
> class SuperType:
> # ...
> def __repr__ (sef):
> return "%s(stuff)" % (self.__class__.__name__, stuff)
... which you do use here.
> But I need each class to know its name. Subtypes are actually
> defined by users (of a lib), presently they are forced to write the
> name explicitely, which is stupid since they already give it as var
> name:
>
> class SubType (SuperType):
> __name__ = "SubType"
> # ....
I do not get it. The __class__.__name__ thing works great for me:
>>> class Foo():
... def whoami(self):
... return self.__class__.__name__
...
>>> f = Foo()
>>> f.whoami()
'Foo'
>>> class Bar(Foo):
... pass
...
>>> b = Bar()
>>> b.whoami()
'Bar'
Please be a bit more specific about your problem, because the problem
you described obviously does not exist ;).
-nik
--
* mirabilos is handling my post-1990 smartphone *
<mirabilos> Aaah, it vibrates! Wherefore art thou, demonic device??
PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 905 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/tutor/attachments/20140102/c6089590/attachment-0001.sig>
More information about the Tutor
mailing list