python类和对象的一些方法(GIF)

1.类和对象的一些GIF

1.1issubclass(类1,类2)

若类1 是类2 的子类,返回True;

>>> class a:
	pass

>>> class b(a):
	pass

>>> issubclass(b,a)
True
>>> issunclass(b,b)
>>> issubclass(b,b)
True

1.2 isinstance(对象,类)

若对象是类的实例化对象,返回True;

>>> class a:
	pass

>>> class b(a):
	pass

>>> b1 = b()
>>> isinstance(b1,b)
True
>>> class c:
	pass

>>> isinstance(b1,(a,b,c))
True

1.3 hasattr(对象,属性)

若该对象有此属性返回True

>>> 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#26>", line 1, in <module>
    hasattr(c1,x)
NameError: name 'x' is not defined

1.4 getattr(对象,属性[,default])

不解释

>>> class c:
	def __init__(self,x=0):
		self.x = x

>>> c1=c()
>>> getattr(c1,'x')
0
>>> getattr(c1,'y',"你所访问的属性不存在....")
'你所访问的属性不存在....'
>>> 

1.5 setattr(object,name,value)

给对象赋予属性name,并附上值value;

>>> setattr(c1,'y','你莫不是想什么呢')
>>> getattr(c1,'y',"你所访问的属性不存在....")
'你莫不是想什么呢'

1.6 delattr(object,name)

删除object中的属性name;

>>> delattr(c1,'y')
>>> delattr(c1,'y')
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    delattr(c1,'y')
AttributeError: y
>>> 

1.7 property()

class c:
	def __init__(self,size=10):
		self.size = size
	def getsize(self):
		return self.size
	def setsize(self,value):
		self.size = value
	def delsize(self):
		del self.size
	x=property(getsize,setsize,delsize)

	
>>> c1 = c()
>>> c1.getsize()
10
>>> c1.x
10
>>> c1.x=18
>>> c1.x
18
>>> c1.size
18
c1.getsize()
18
>>> del c1.x
>>> c1.size
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    c1.size
AttributeError: 'c' object has no attribute 'size'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值