首页 > 代码库 > 特殊方法-0505-2017

特殊方法-0505-2017

#特殊方法
class Rectangle():
def __init__(self,width,height):
self.width = width
self.height = height
#def __str__(self): #print调用方法
#return‘宽%s,高%s‘%(self.width,self.height)

#def __repr__(self):#repr会影响print
#return ‘面积为%s‘%self.area()
@property
def area(self):
return self.width*self.height

def __call__(self): #用了call方法,可以调用实例c1()
return ‘dsfsf‘

def __add__(self,other):#另外一个实例名为other
if isinstance(other,Rectangle): #判断两者是一类
return self.area() + other.area()
@staticmethod

def fun(): #没有self
return ‘dafaf‘
@classmethod   #这样可以被类调用
def show(cls):
print(cls)#cls表示类和self一样
return ‘fdfdf‘
c1 = Rectangle(3,4)
c2 = Rectangle(5,6)
#str这个类有两个方法,一个是__str__,__repr__
#__repr__会影响__str__
#如字符串 s = ‘avf\nd‘
#s= avf\nd
#print(s),会变成 avf 换行 d.print调用的是str方法
#isinstance(实例,类名)判断是不是这个类用

#property装饰器,将方法当做属性
#staticmethod把不是实例的实例化,进行调用
#有self的只能被实例调用,没有self的可以被实例和类使用

特殊方法-0505-2017