python 类方法与静态方法

类方法与静态方法

class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day =  day
    # echo普通方法, 默认情况下会传递对象给echo
    def echo(self):
        return  "%s %s %s" %(self.year, self.month, self.day)

    # 默认传递类本身给这个方法;
    @classmethod
    def as_string(cls,s):
        print(cls)
        month, day, year = s.split('/')
        d = cls(year, month, day)
        return d
    #  默认python解释器不会传递任何参数
    @staticmethod
    def is_vaild(s):
        # 批量将年月日转换成整形(列表生成式, map)
        # month, day, year = s.split('/')
        # month, day, year = [int(i) for i in s.split('/')]
        month, day, year = map(int, s.split('/'))
        return 0 < month <= 12 and 0 < day <= 31 and 1 < year < 9999
    #
# d = Date(2018, 10, 10)
# d.echo()


s = '10/10/2018'
# print(as_string('12/10/2019').echo())

print(Date.as_string(s).echo())
#
# s = '10/10/2018'
print(Date.is_vaild(s))
#
#
d = Date(2018, 10, 10)
print(d.is_vaild('13/10/2019'))

python 类方法与静态方法_第1张图片

with语句

# # 上下文管理协议
# #   1). 当with语句开始运行的时候,执行什么方法;
# #   2). 当with语句执行结束之后出发某个方法的运行;
# with open('/etc/passwd') as f:
#     print(f.read())


class MyOpen(object):
    def __init__(self, filename, mode='r'):
        self._name = filename
        self._mode = mode
    # 当with语句开始运行的时候,执行什么方法;
    def __enter__(self):
        self.f = open(self._name, self._mode)
        return  self.f
    # 当with语句执行结束之后出发某个方法的运行;
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

    @property
    def name(self):
        return  self._name
    @property
    def mode(self):
        return  self._mode


with MyOpen('/etc/passwd')   as f:
    print(f.closed)
    print(f.read(5))


print(f.closed)
# with open('/etc/passwd') as f:

你可能感兴趣的:(python 类方法与静态方法)