python基本学习-类的方法

来源:互联网 发布:淘宝商城女装韩版 编辑:程序博客网 时间:2024/06/05 14:18

类方法 @classmethod :绑定类

实例方法:绑定实例对象

静态方法 @staticmethod : 无绑定

特殊方法(魔法方法), init

class Date(object):    def __init__(self,day,month,year):        self.day = day        self.month = month        self.year = year    def __str__(self):        return "{0}-{1}-{2}".format(self.year,self.month,self.year)    @classmethod    def from_string(cls,date_as_string):        year.month,day = map(int,date_as_string.split('-'))        date1 = cls(day,month,year)        return date1        #返回取决于调用的类cls    @staticmethod    def is_date_valid(date_as_string):        year,month,day = map(int,date_as_string.split('-'))        return day<=31 and month <=12 and year<=3999    @staticmethod    def millenium(month,day):        return Date(month,day,2000)class DateTime(Date):    def __str__(self):        return "{0}-{1}-{2}-00:00:00PM".format(self.year,self.month,self.year)

特殊方法

  • 属性访问:getattr,setattr,
  • 实例生成/类生成: init, new
  • 数字计算: add, sub, mul,div,pow,round
  • 调用方法: str,repr,len,bool
  • 比较大小:cmp,lt,le,eq,ne,gt,ge
  • 集合访问:setslice,getslice,getitem,setitem,contains
  • 迭代器: iter,next
class Point(object):    def __init__(self,x,y):        self.x = x         self.y = y     def __sub__(self,other):        assert isinstance(other,Point)#判断传入的数据是否为Point类        return Point(self.x+other.x,self.y+other.y)    @property    def xy(self):        return (self.x,self.y)    def __str__(self):  # 显示print(a-b)结果        return "x={0},y={1}".format(self.x,self.y)    def __repr__(self): #显示 a-b的解结果        return str(self.xy)# a = Point(50,60)# b = Point(30,40)# a - b     
原创粉丝点击