python语言中type是什么意思_Python中的“Type”和“Object”有什么区别

下面是对这两个函数的简单探讨。我觉得做这个练习很有启发性。我经常会创建一个简单的程序来探索简单函数的来龙去脉,并将它们保存起来以供参考:#

# Testing isinstance and issubclass

#

class C1(object):

def __init__(self):

object.__init__(self)

class B1(object):

def __init__(self):

object.__init__(self)

class B2(B1):

def __init__(self):

B1.__init__(self)

class CB1(C1,B1):

def __init__(self):

# not sure about this for multiple inheritance

C1.__init__(self)

B1.__init__(self)

c1 = C1()

b1 = B1()

cb1 = CB1()

def checkInstanceType(c, t):

if isinstance(c, t):

print c, "is of type", t

else:

print c, "is NOT of type", t

def checkSubclassType(c, t):

if issubclass(c, t):

print c, "is a subclass of type", t

else:

print c, "is NOT a subclass of type", t

print "comparing isinstance and issubclass"

print ""

# checking isinstance

print "checking isinstance"

# can check instance against type

checkInstanceType(c1, C1)

checkInstanceType(c1, B1)

checkInstanceType(c1, object)

# can check type against type

checkInstanceType(C1, object)

checkInstanceType(B1, object)

# cannot check instance against instance

try:

checkInstanceType(c1, b1)

except Exception, e:

print "failed to check instance against instance", e

print ""

# checking issubclass

print "checking issubclass"

# cannot check instance against type

try:

checkSubclassType(c1, C1)

except Exception, e:

print "failed to check instance against type", e

# can check type against type

checkSubclassType(C1, C1)

checkSubclassType(B1, C1)

checkSubclassType(CB1, C1)

checkSubclassType(CB1, B1)

# cannot check type against instance

try:

checkSubclassType(C1, c1)

except Exception, e:

print "failed to check type against instance", e

编辑:

还应考虑以下问题,因为isinstance可能会破坏API实现。例如,一个对象的行为类似于字典,但不是从dict派生的。isinstance可能会检查对象是否是字典,即使该对象支持字典样式的访问:

isinstance considered harmful

编辑2:Can someone please give me an example of a distinction between passing a Type as a second argument versus passing an Object?

在测试了上面的代码之后,它告诉我第二个参数必须是一个类型。所以在以下情况下:

^{pr2}$

呼叫将失败。可以这样写:checkInstanceType(c1, type(b1))

因此,如果要检查一个实例与另一个实例的类型,则必须使用type()内置调用。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值