类方法和静态方法

本文介绍了Python中三种方法类型的使用方式及其特点:普通方法、类方法和静态方法。通过实例展示了如何利用这些方法来增强代码的组织性和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过静态方法和类方法能够把相关的函数封装到一个类里面,有效的将代码组织起来, 提高代码的可维护性;

普通方法:

class Date(object):
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    ##普通方法
    def __echo__(self):
        print """
        Day:%.2d
        Month:%.2d
        Year:%.4d
        """%(self.day,self.month,self.year)

d=Date(2018,4,3)
d.__echo__()

这里写图片描述

类方法:

class Date(object):
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    ##普通方法
    def __echo__(self):
        print """
        Day:%.2d
        Month:%.2d
        Year:%.4d
        """%(self.day,self.month,self.year)
    @classmethod
    def str_date(cls,s):
        year,month,day=map(int,s.split("-"))
        d=cls(year,month,day)
        return d

# d=Date(2018,4,3)
# d.__echo__()

d=Date.str_date("2018-4-3")   ###类调用str_date方法
print d
d.__echo__()
---->>
<__main__.Date object at 0x7f7f8da69e50>

        Day:03
        Month:04
        Year:2018

这里写图片描述

静态方法

class Date(object):
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    def __echo__(self):
        print """
        Day:%.2d
        Month:%.2d
        Year:%.4d
        """%(self.day,self.month,self.year)
    @classmethod
    def str_date(cls,s):
        year,month,day=map(int,s.split("-"))
        d=cls(year,month,day)
        return d
    @staticmethod
    def is_legal(s):
        year, month, day = map(int, s.split('-'))
        if not 0 < month <= 12 and 0 < day <= 31:
            print '%s不合法' % s
        else:
            print '%s合法' % s
d=Date.is_legal("2018-1-3")
---->>>
2018-1-3合法

这里写图片描述

小结

普通方法: 没有@classmethod装饰器; 默认第一个参数是self(<__main__.Date object>); 调用时, 对象调用普通方法;
类方法: 有@classmethod装饰器; 默认第一个参数是cls(\<__main__.Date’>); 调用时, 类调用类方法;
静态方法:有@staticmethod装饰器,默认参数为可变参数,调用时,类调用静态方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值