python基本学习-类的方法

类方法 @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     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值