type(obj) 和 obj.__class__ 的区别 [英] Difference between type(obj) and obj.__class__
本文介绍了type(obj) 和 obj.__class__ 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
type(obj)
和 obj.__class__
有什么区别?有没有可能 type(obj) is not obj.__class__
?
我想编写一个对提供的对象通用的函数,使用与另一个参数相同类型的默认值 1.下面的#1 或#2 哪个变体会做正确的事情?
def f(a, b=None):如果 b 是 None:b = type(a)(1) # #1b = a.__class__(1) # #2
解决方案
type(obj)
和 type.__class__
对于旧样式类的行为不同:
What is the difference between type(obj)
and obj.__class__
? Is there ever a possibility of type(obj) is not obj.__class__
?
I want to write a function that works generically on the supplied objects, using a default value of 1 in the same type as another parameter. Which variation, #1 or #2 below, is going to do the right thing?
def f(a, b=None):
if b is None:
b = type(a)(1) # #1
b = a.__class__(1) # #2
解决方案
type(obj)
and type.__class__
do not behave the same for old style classes:
>>> class a(object):
... pass
...
>>> class b(a):
... pass
...
>>> class c:
... pass
...
>>> ai=a()
>>> bi=b()
>>> ci=c()
>>> type(ai) is ai.__class__
True
>>> type(bi) is bi.__class__
True
>>> type(ci) is ci.__class__
False
这篇关于type(obj) 和 obj.__class__ 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文