zoukankan      html  css  js  c++  java
  • Python staticmethod

    1 @staticmethod 静态方法

    when this method is called, we don't pass an instance of the class to it (as we normally do with methods).
    This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).
    当这个方法被调用时,我们不会将类的实例传递给它(就像我们通常用方法做的那样)。
    这意味着你可以在一个类中放入一个函数,但是你不能访问该类的实例(当你的方法不使用实例时这很有用)

    关于参数:该方法不强制要求传递参数,(如不需要表示自身对象的self自身类的cls参数,就跟使用函数一样。)

    如下声明一个静态方法:

    class C(object):
        @staticmethod
        def f(arg1, arg2, ...):
            ...

    以上实例声明了静态方法 f,类可以不用实例化就可以调用该方法 C.f(),当然也可以实例化后调用 C().f()

    函数语法:staticmethod(function)

    例如:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class C(object):
        @staticmethod
        def f():
            print('runoob');
     
    C.f();          # 静态方法无需实例化
    cobj = C()
    cobj.f()        # 也可以实例化后调用

    又如:

    # 类中
        @staticmethod
        def is_date_valid(date_as_string):
            day, month, year = map(int, date_as_string.split('-'))
            return day <= 31 and month <= 12 and year <= 3999
    
    # usage:
    is_date = Date.is_date_valid('11-09-2012')

     这里结果(is_date)是True/False

    2 @classmethod 类方法

    when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). 
    This means you can use the class and its properties inside that method rather than a particular instance.
    当调用此方法时,我们将该类作为第一个参数传递,而不是该类的实例(正如我们通常对方法所做的那样)。
    这意味着您可以在该方法内使用该类及其属性,而不能使用特定的实例


    关于参数:该方法强制要求传递一个必须参数, 不需要self参数,但第一个参数需要是表示自身类的cls参数。

    如:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class A(object):
        bar = 1
        def func1(self):  
            print ('foo') 
        @classmethod
        def func2(cls):
            print ('func2')
            print (cls.bar)
            cls().func1()   # 调用 foo 方法
     
    A.func2()               # 不需要实例化

     

     例如:

    # 类中
    @classmethod
    def from_string(cls, date_as_string): day, month, year = map(int, date_as_string.split('-')) date1 = cls(day, month, year) return date1 date2 = Date.from_string('11-09-2012')

    这里结果(date2)是一个Date的实例。

    他有如下好处:

    1. We've implemented date string parsing in one place and it's reusable now.
    2. Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits OOP paradigm far better).
    3. cls is an object that holds class itself, not an instance of the class. It's pretty cool because if we inherit our Date class, all children will have from_string defined also.

     简单来说就是,可以有无限的from_string方法。

    3 实例方法

    4 最后:

    使用@classmethod或@staticmethod都可以类名.方法名()调用函数

     前者必须要一个类参数,后者可以不必须要参数

    class Date(object):
    
        def __init__(self, day=0, month=0, year=0):
            self.day = day
            self.month = month
            self.year = year
    
        @classmethod
        def from_string(cls, date_as_string):
            day, month, year = map(int, date_as_string.split('-'))
            date1 = cls(day, month, year)
            return date1
    
        @staticmethod
        def is_date_valid(date_as_string):
            day, month, year = map(int, date_as_string.split('-'))
            return day <= 31 and month <= 12 and year <= 3999
    
    date2 = Date.from_string('11-09-2012')
    is_date = Date.is_date_valid('11-09-2012')
  • 相关阅读:
    【C#】:浅谈反射机制 【转】
    ArcGIS Server 10中的切图/缓存机制深入【转】
    ArcGIS Server的切图原理深入【转】
    【OpenGL】用OpenGL shader实现将YUV(YUV420,YV12)转RGB-(直接调用GPU实现,纯硬件方式,效率高)
    MFC 带Ribbonbar的窗口 实现全屏和取消全屏
    C#.net开发 List与DataTable相互转换 【转】
    Net编程 详解DataTable用法【转】
    三维空间两直线/线段最短距离、线段计算算法 【转】
    OSG立体模式下动态修改相机远近裁剪面的实现
    用curl去探测接口是否正常返回结果,若没有正常返回则触发报警
  • 原文地址:https://www.cnblogs.com/cymwill/p/8723462.html
Copyright © 2011-2022 走看看