type(obj) 和 obj.__class__ 的区别 [英] Difference between type(obj) and obj.__class__

查看:74
本文介绍了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__ 对于旧样式类的行为不同:

<预><代码>>>>a类(对象):... 经过...>>>b(a)类:... 经过...>>>c类:... 经过...>>>ai=a()>>>双=b()>>>ci=c()>>>type(ai) 是 ai.__class__真的>>>type(bi) 是 bi.__class__真的>>>type(ci) 是 ci.__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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆