python类的方法

  • Post author:
  • Post category:python



Python类的语法中有三种方法:实例方法,静态方法,类方法。


我们在学习python类,定义方法时括号里的


self


总是让人有点迷糊,看如下代码(每个方法的功能都是返回当前时间戳)

import time

class TimeStamp(object):
    def timestamp(self):
        ts = time.time()
        timestamp = round(ts * 1000)
        return timestamp

    @staticmethod
    def s_timestamp():
        ts = time.time()
        timestamp = round(ts * 1000)
        return timestamp

    @classmethod
    def c_timestamp(cls):
        cls.ts = time.time()
        timestamp = round(cls.ts * 1000)
        return timestamp

if __name__ == '__main__':
    a = TimeStamp()
    print(a.timestamp())
    print(TimeStamp.s_timestamp())
    print(TimeStamp.c_timestamp())    

  • 实例方法:


    第一个参数必须要默认传实例对象,一般习惯用self;实例方法只能被类的实例对象调用。

  • 静态方法:


    参数没有要求,可以空(由


    @staticmethod


    装饰);静态方法可以被类或类的实例对象调用。

  • 类方法:


    第一个参数必须要默认传类,一般习惯用cls(由


    @classmethod


    装饰);类方法可以被类或类的实例对象调用。


还有一类特殊的方法:

属性

(由


@property


装饰)

import time

class TimeStamp(object):
    @property
    def p_timestamp(self):
        ts = time.time()
        timestamp = round(ts * 1000)
        return timestamp

if __name__ == '__main__':
    a = TimeStamp()
    print(a.p_timestamp)


使用


@property


装饰器会将方法转换为相同名称的只读属性,这样可以防止属性被修改。



总结 :


属性与实例方法差不多,第一个参数也是默认传实例对象,只能被实例对象调用;不同之处在于调用属性时方法名后不需带括号()。


类的方法只是在定义上、访问类变量和调用时有些许差别,开发者可以根据个人习惯自由使用,项目本身没有限制。



版权声明:本文为cbc520原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。