• python中的静态方法和类方法


    在python中,各种方法的定义如下所示:


    class MyClass(object):
    #在类中定义普通方法,在定义普通方法的时候,必须添加self
        def foo(self,x):
            print "this is a method  %s %s"  % (self,x)
        
    #在类中定义静态方法,在定义静态方法的时候,不需要传递任何类的东西
        @staticmethod
        def static_method(x):
            print "this is a static method: %s " % x
    
    
    #在类中定义类方法,在定义类方法的时候,需要传递参数cls
        @classmethod
        def class_method(cls,x):
            print "this is a class method: %s %s" %(cls,x)

    1、 在定义普通方法的时候,需要的参数是self,也就是把类的实例作为参数传递给方法,如果在不写self的时候,会发现报错TypeError错误,表示传递参数多了,其实也就是在调用类方法的时候,将实例作为参数传递了。

    在使用普通方法的时候,必须是使用实例来调用方法,不能使用类来调用方法,没有实例,那么方法将无法调用。


    2、 在定义静态方法的时候,和模块中的方法没有什么不同,最大的不同就在于静态方法在类的命名空间之中,并且在声明静态方法的时候,使用的标记为@staticmethod,表示为静态方法,在调用静态方法的时候,可以使用类名或者是实例名来进行调用,一般使用类名来进行调用

    静态方法主要是用来放一些方法,方法的逻辑属于类,但是又和类本身没有交互,从而形成了静态方法,主要是让静态方法放在此类的名称空间之内,从而能够更加有组织性。


    3、 在定义类方法的时候,传递的参数为cls,表示为类,此写法也可以变,但是一般写为cls。类的方法调用可以使用类,也可以使用实例,一般的情况下是使用类。


    4、 self表示为类型为类的object,而cls表示为类也就是class


    5、在继承的时候,静态方法和类方法都会被子类继承。在进行重载类中的普通方法的时候,只要 写上相同的名字即可进行重载。


    6、 在重载调用父类方法的时候,最好是使用super来进行调用父类的方法。

    静态方法主要用来存放逻辑性的代码,基本在静态方法中,不会涉及到类的方法和类的参数。

    类方法是在传递参数的时候,传递的是类的参数,参数是必须在cls中进行隐身穿


    class Date(object):
        day  = 0
        month = 0
        year = 0
    
    #define the init parameter
        def __init__(self,day=0,month=0,year=0):
            self.day = day
            self.month = month
            self.year = year
    
    #this is for the class method ,and the method is use parameter
    #this must use the parameter of the self,this is for the object
        def printf(self):
            print "the time is %s %s %s " %(self.day,self.month,self.year)
    
    #this is define a classmethod,and the praemter have a cls,and can use the cls to create a class
    #cls is passed of the class,then can initiate the object
        @classmethod
        def from_string(cls,date_as_string):
            day,month,year = map(int,date_as_string.split("-"))
            date1 = cls(day,month,year)
            date1.printf()
    
    #this is the static method,and thre is do something to manage the logic,not the class or object
        @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



    for linux and python
  • 相关阅读:
    [mysql] 删除唯一约束unique
    onethink 路由规则无效问题解决
    mysql source 乱码
    NLPIR
    词性标记集--计算所汉语
    [thinkphp] 无限极分类
    UITableViewCell在非Nib及Cell重用下设置CellStyle
    UIViewController的初始化
    转:NSString / NSData / char* 类型之间的转换
    转:苹果Xcode帮助文档阅读指南
  • 原文地址:https://www.cnblogs.com/kellyseeme/p/5525062.html
Copyright © 2020-2023  润新知