[Tutor] what's your name? (to a class)

eryksun eryksun at gmail.com
Thu Jan 2 16:48:24 CET 2014


On Thu, Jan 2, 2014 at 5:12 AM, spir <denis.spir at gmail.com> wrote:
>
> 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?

What are you smoking, and where can I get some? ;)

Actually, I think I understand the source of your confusion. `dir`
doesn't show attributes from the metaclass because that would be too
confusing.

__class__ is a descriptor in the dict of `type`:

    >>> name = vars(type)['__name__']
    >>> type(name)
    <class 'getset_descriptor'>

    >>> class C: pass
    ...
    >>> name.__get__(C)
    'C'

For a heap type, the getter can just return the Python object
`ht_name`. For a built-in type it has to construct a Unicode string
(assuming 3.x) from the `tp_name` slot.

The setter (`type_set_name`) won't let you change the name of a
built-in type. It also has to ensure that the name doesn't contain a
null:

    >>> name.__set__(C, 'GoodName')
    >>> C.__name__
    'GoodName'

    >>> name.__set__(int, 'float')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can't set int.__name__

    >>> name.__set__(C, 'Bad\x00Name')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: __name__ must not contain null bytes

    >>> name.__set__(C, 'Really Weird Name')
    >>> C.__name__
    'Really Weird Name'


More information about the Tutor mailing list