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

    科技2022-07-16  133

    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'
    Processed: 0.009, SQL: 8