현재 수업 이름을 얻으시겠습니까?
현재 수업 이름을 어떻게 알 수 있습니까?
예:
def get_input(class_name):
[do things]
return class_name_result
class foo():
input = get_input([class name goes here])
내가 (vistrails) 인터페이스하고있는 프로그램의 특성으로 인해을 (를) __init__()
초기화 하는 데 사용할 수 없습니다 input
.
obj.__class__.__name__
개체 이름을 가져 오므로 다음과 같이 할 수 있습니다.
class Clazz():
def getName(self):
return self.__class__.__name__
용법:
>>> c = Clazz()
>>> c.getName()
'Clazz'
클래스 본문 내에서 클래스 이름이 아직 정의되지 않았으므로 사용할 수 없습니다. 단순히 수업 이름을 입력 할 수 없습니까? 해결책을 찾을 수 있도록 문제에 대해 더 많이 말해야 할 수도 있습니다.
이 작업을 수행하기 위해 메타 클래스를 만들 것입니다. 클래스 생성시 (개념적으로 class : block의 맨 끝에서) 호출되며 생성되는 클래스를 조작 할 수 있습니다. 나는 이것을 테스트하지 않았습니다.
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__
편집하다:
As said by Ned Batcheler
, this wouldn't work in the class body, but it would in a method.
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'
>>>
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.
It is accessible from within the very definition of a class or a function, so for instance:
class Foo:
print(__qualname__)
will effectively print Foo
. You'll get the fully qualified name (excluding the module's name), so you might want to split it on the .
character.
However, there is no way to get an actual handle on the class being defined.
>>> class Foo:
... print('Foo' in globals())
...
False
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__)
참고URL : https://stackoverflow.com/questions/6943182/get-name-of-current-class
'Programing' 카테고리의 다른 글
~ / Library / Developer / Xcode / DerivedData 디렉토리에서 안전하게 삭제하려면 어떻게해야합니까? (0) | 2020.09.11 |
---|---|
xsl : value-of select = "…에 문자열을 연결하는 방법? (0) | 2020.09.11 |
pdb를 종료하고 프로그램을 계속하는 방법은 무엇입니까? (0) | 2020.09.11 |
iOS에서 프로그래밍 방식으로 이미지에 색조를 지정하려면 어떻게해야합니까? (0) | 2020.09.11 |
원시 16 비트 x86 기계어 코드를 어떻게 분해합니까? (0) | 2020.09.11 |