首页 > 其他 > 详细

特殊方法-0505-2017

时间:2017-05-05 22:27:25      阅读:259      评论:0      收藏:0      [点我收藏+]

#特殊方法
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

原文:http://www.cnblogs.com/87Sarah/p/6815123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!