A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/14513019/python-get-class-name below:

Python get class name - Stack Overflow

Other than the metaclass in F J's answer, I can think of two other ways. I'll start with the nicer looking one. You don't need to use a metaclass; sometimes a descriptor is perfectly adequate.

class ClassNameDescriptor(object):
    def __get__(self, instance, owner):
        return owner.__name__

class BaseClass(object):
    name = ClassNameDescriptor()

class Foo(BaseClass):
    pass

The other way, if you really need the class name from inside the class body (unlikely), you can snoop on the call stack. The class name, as it appears in source, is on the code object being executed by the class definition:

import sys

def get_class_name_from_inside_class():
    return sys._getframe().f_back.f_code.co_name

class Foo(object):
    name = get_class_name_from_inside_class()
    print name

Of the ones presented so far, only this last one allws you to use the name, as a string, from inside the class body, Unfortunately, this doesn't work in all versions of python, notably IronPython does not implementent the call stack introspection as it's not available in the DLR.

There's a way to get it without introspecting the stack, portably. It's similar to the answer provided by F J, using a metaclass, but instead uses the __prepare__ feature available in Python 3:

class namedMeta(type):
    def __prepare__(mcls, name, bases, **kwargs):
        return {'name': name}

class Foo(metaclass=named):
    print name

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4