|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 游戏小虾米 于 2017-7-23 01:45 编辑
Tip:
一,理论
二,应用
1 issubclass(class, classinfo)
>>> class A:
pass
>>> class B(A):
pass
>>> issubclass(A, B)
False
>>> issubclass(B, A)
True
2 isinstance(object, classinfo) #第一个不是object,永远传回false,第二个不是class类型,会有TypeError异常
>>> isinstance(B, A)
False
>>> b1 = B()
>>> isinstance(b1, B)
True
>>> isinstance(b1, b1)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
isinstance(b1, b1)
TypeError: isinstance() arg 2 must be a type or tuple of types
3 hasattr(object, name) #name必须为字符串形式
>>> class C:
def __init__(self, x=0):
self.x = x
>>> c1 = C()
>>> hasattr(c1, 'x')
True
>>> hasattr(c1, x)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
hasattr(c1, x)
NameError: name 'x' is not defined
4 getattr(object, name[, default])
>>> getattr(c1, 'x')
0
>>> getattr(c1, 'y')
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
getattr(c1, 'y')
AttributeError: 'C' object has no attribute 'y'
>>> getattr(c1, 'y','访问不存在')
'访问不存在'
5 setattr(object, name, value)
>>> setattr(c1, 'y', 'FishC')
>>> getattr(c1, 'y','访问不存在')
'FishC'
6 delattr(object, name)
>>> delattr(c1, 'y')
>>> delattr(c1, 'y')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
delattr(c1, 'y')
AttributeError: y
7 property(getattr, setattr, delattr, doc)
>>> class C:
def __init__(self, size = 10):
self.size = size
def getattr(self):
return self.size
def setattr(self, size):
self.size = size
def delattr(self):
del self.size
x = property(getattr, setattr, delattr)
>>> c1 = C()
>>> c1.getattr()
10
>>> c1.x
10
>>> c1.x = 20
>>> c1.x
20
>>> del c1.x
>>> c1.x
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
c1.x
File "<pyshell#47>", line 5, in getattr
return self.size
AttributeError: 'C' object has no attribute 'size'
三,课后练习 |
评分
-
查看全部评分
|