我有很多类代码都是这样的。每个__init__
启动一个线程和一个具有该类名称的记录器。如何在__init__
内以字符串形式获取当前类的名称?请注意,self
可能不是当前类的实例,因此以下内容并非万无一失。
from threading import Thread
import logging
def myClassName(myclass):
myclass._class_name = myclass.__name__
return myclass
@myClassName
class SomeClass(object):
def __init__(self):
class_name = type(self)._class_name
print "My class name in __init__ is", class_name
self.thread = Thread(name=class_name)
self.logger = logging.getLogger(class_name)
更新
澄清:
答案 0 :(得分:3)
在Python 3中,这非常简单,我们可以使用__class__
单元格变量来获取当前类。
在Python 2中,我们可以通过使用元类在函数globals范围中注入类的名称并稍后清理它来实现类似的东西。
from functools import wraps
from types import FunctionType
def decorate(func, class_name):
@wraps(func)
def wrapper(*args, **kwargs):
sentinel = object()
actual_value = func.__globals__.get('__class__', sentinel)
func.__globals__['__class__'] = class_name
try:
result = func(*args, **kwargs)
finally:
if actual_value is sentinel:
del func.__globals__['__class__']
else:
func.__globals__['__class__'] = actual_value
return result
return wrapper
class Meta(type):
def __new__(cls, name, bases, attrs):
for k, v in attrs.items():
if isinstance(v, FunctionType):
attrs[k] = decorate(v, name)
return type.__new__(cls, name, bases, attrs)
class A:
__metaclass__ = Meta
def func(self):
print(__class__)
print('Inside A')
class B(A):
def func(self):
print(__class__)
print('Inside B')
super(B, self).func()
B().func()
<强>输出:强>
B
Inside B
A
Inside A
要将__class__
变量作为类对象本身,我们可以进行一些更改:
def decorate(func, cls):
@wraps(func)
def wrapper(*args, **kwargs):
sentinel = object()
actual_value = func.__globals__.get('__class__', sentinel)
func.__globals__['__class__'] = cls
try:
result = func(*args, **kwargs)
finally:
if actual_value is sentinel:
del func.__globals__['__class__']
else:
func.__globals__['__class__'] = actual_value
return result
return wrapper
class Meta(type):
def __new__(cls, name, bases, attrs):
cls = type.__new__(cls, name, bases, attrs)
for k, v in attrs.items():
if isinstance(v, FunctionType):
setattr(cls, k, decorate(v, cls))
return cls
现在输出将是:
<class '__main__.B'>
Inside B
<class '__main__.A'>
Inside A
答案 1 :(得分:2)
您可以检索对象类的名称:
obj.__class__.__name__
示例:
class SomeClass(object):
def __init__(self):
print("I am a %s"%self.__class__.__name__)
class Derived(SomeClass):
pass
x = SomeClass()
y = Derived()
结果:
$ python x.py
I am a SomeClass
I am a Derived