得到当前类的名称?

如何获取当前所在类的名称?

例如:

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


class foo():
input = get_input([class name goes here])

由于我接口的程序的性质(vistrails) ,我不能使用 __init__()来初始化 input

129054 次浏览

在类的主体中,类名尚未定义,因此不可用。您不能简单地键入类的名称吗?也许你需要多谈谈这个问题,这样我们才能为你找到解决办法。

我将创建一个元类来为您完成这项工作。它在类创建时调用(概念上在类: 块的最后) ,并且可以操作正在创建的类。我还没测试过:

class InputAssigningMetaclass(type):
def __new__(cls, name, bases, attrs):
cls.input = get_input(name)
return super(MyType, cls).__new__(cls, name, bases, newattrs)


class MyBaseFoo(object):
__metaclass__ = InputAssigningMetaclass


class foo(MyBaseFoo):
# etc, no need to create 'input'


class foo2(MyBaseFoo):
# etc, no need to create 'input'

您可以通过类的私有属性访问它:

cls_name = self.__class__.__name__

编辑:

正如 Ned Batchelder所说,这在类主体中不会起作用,但在方法中会起作用。

obj.__class__.__name__将得到任何对象的名称,因此可以这样做:

class Clazz():
def getName(self):
return self.__class__.__name__

用法:

>>> c = Clazz()
>>> c.getName()
'Clazz'

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'

然而,我不会这样做; 我的原始答案仍然是我自己的偏好作为一个解决方案。原始答案:

可能最简单的解决方案是使用一个装饰器,这与 Ned 关于元类的回答类似,但是功能不那么强大(装饰器可以使用黑魔法,但是元类可以使用 古老,神秘黑魔法)

>>> 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'
>>>
import sys


def class_meta(frame):
class_context = '__module__' in frame.f_locals
assert class_context, 'Frame is not a class context'


module_name = frame.f_locals['__module__']
class_name = frame.f_code.co_name
return module_name, class_name


def print_class_path():
print('%s.%s' % class_meta(sys._getframe(1)))


class MyClass(object):
print_class_path()

I think, it should be like this:

    class foo():
input = get_input(__qualname__)

PEP 3155 introduced __qualname__, which was implemented in Python 3.3.

For top-level functions and classes, the __qualname__ attribute is equal to the __name__ attribute. For nested classes, methods, and nested functions, the __qualname__ attribute contains a dotted path leading to the object from the module top-level.

它可以从类或函数的定义中访问,例如:

class Foo:
print(__qualname__)

将有效地打印 Foo。 您将获得完全限定名(不包括模块的名称) ,因此您可能需要将其分割为 .字符。

但是,无法获得正在定义的类的实际句柄。

>>> class Foo:
...     print('Foo' in globals())
...
False

@Yuval Adam answer using @property

class Foo():
@property
def name(self):
return self.__class__.__name__


f = Foo()
f.name  # will give 'Foo'


I'm using python3.8 and below is example to get your current class name.

class MyObject():
@classmethod
def print_class_name(self):
print(self.__name__)


MyObject.print_class_name()

或者不使用@classmethod

class ClassA():
def sayhello(self):
print(self.getName())
    

def getName(self):
return self.__class__.__name__


ClassA().sayhello()

希望能帮助别人! ! !