Python:self.__class__ vs. type(self)

标签 python

我想知道两者之间是否有区别

class Test(object):
    def __init__(self):
        print self.__class__.__name__

class Test(object):
    def __init__(self):
        print type(self).__name__

?

有理由偏爱其中一个吗?

(在我的用例中,我想用它来确定记录器名称,但我想这并不重要)

最佳答案

>>> class Test(object): pass
>>> t = Test()
>>> type(t) is t.__class__
True
>>> type(t)
__main__.Test

所以这两个是一样的。 我会使用 self.__class__ 因为它更明显。

但是,type(t) 不适用于旧式类,因为旧式类的实例类型是 instance,而一个新样式的类实例是它的类:

>>> class Test(): pass
>>> t = Test()
>>> type(t) is t.__class__
False
>>> type(t)
instance

关于Python:self.__class__ vs. type(self),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10386166/

相关文章:

python - 更改收到的 JSON 数据

python - 防止 matplotlib 将我的轴重新设置为零

Python2字输入if语句脚本

python - Python 模块是如何工作的

python - R 的可训练 sklearn StandardScaler

python - 创建两个 TensorFlow session 时是否会创建图的多个实例?

c++ - SWIG 无法正确转换 typedef 类型

python - 如何使用 Boost Python 将 C++ bool 转换为 Python boolean?

python - 我该如何解决这个无法导入错误: cannot import name in python3

Python,matplotlib : how to set tick label values to their logarithmic values