Get name of current class?

后端 未结 7 2194
有刺的猬
有刺的猬 2020-12-04 23:21

How do I get the name of the class I am currently in?

Example:

def get_input(class_name):
    [do things]
    return class_name_result

class foo():
         


        
7条回答
  •  误落风尘
    2020-12-04 23:29

    EDIT: Yes, you can; but you have to cheat: The currently running class name is present on the call stack, and the traceback module allows you to access the stack.

    >>> import traceback
    >>> def get_input(class_name):
    ...     return class_name.encode('rot13')
    ... 
    >>> class foo(object):
    ...      _name = traceback.extract_stack()[-1][2]
    ...     input = get_input(_name)
    ... 
    >>> 
    >>> foo.input
    'sbb'
    

    However, I wouldn't do this; My original answer is still my own preference as a solution. Original answer:

    probably the very simplest solution is to use a decorator, which is similar to Ned's answer involving metaclasses, but less powerful (decorators are capable of black magic, but metaclasses are capable of ancient, occult black magic)

    >>> def get_input(class_name):
    ...     return class_name.encode('rot13')
    ... 
    >>> def inputize(cls):
    ...     cls.input = get_input(cls.__name__)
    ...     return cls
    ... 
    >>> @inputize
    ... class foo(object):
    ...     pass
    ... 
    >>> foo.input
    'sbb'
    >>> 
    

提交回复
热议问题