Python:staticmethod vs classmethod

Being educated under Java background, static method and class method are the same thing.

But not so in Python, there is subtle difference:

Say function a() is defined in Parent Class, while Sub Class extends Parent Class

  • If function a() has @staticmethod decorator, Sub.a() still refers to definition inside Parent Class. Whereas,
  • If function a() has @classmethod decorator, Sub.a() will points definition inside Sub Class.

Let’s talk about some definitions here:

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.

@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).

Let‘s assume an example of a class, dealing with date information (this is what will be our boilerplate to cook on):

classDate(object):

    day =0
    month =0
    year =0

  def __init__(self, day=0, month=0, year=0):self.day = day
        self.month = month
        self.year = year

This class obviously could be used to store information about certain dates (without timezone information; let‘s assume all dates are presented in UTC).

Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typicalinstancemethod, having the first non-optional argument (self) that holds reference to a newly created instance.

Classmethod

We have some tasks that can be nicely done using classmethods.

Let‘s assume that we want to create a lot of Date class instances having date information coming from outer source encoded as a string of next format (‘dd-mm-yyyy‘). We have to do that in different places of our source code in project.

So what we must do here is:

  1. Parse a string to receive day, month and year as thee integer variables or a 3-item tuple consisting of that variable.
  2. Instantiate Date by passing those values to initialization call.

This will look like:

day, month, year = map(int, string_date.split(‘-‘))
date1 =Date(day, month, year)

For this purpose, C++ has such feature as overloading, but Python lacks that feature- so here‘s whenclassmethod applies. Lets create another "constructor".

@classmethoddef 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‘)

Let‘s look more carefully at the above implementation, and review what advantages we have here:

  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 elsewher, 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 ourDate class, all children will have from_string defined also.

Staticmethod

What about staticmethod? It‘s pretty similar to classmethod but doesn‘t take any obligatory parameters (likeclassmethod or instancemethod does).

Let‘s look at the next use case.

We have a date string that we want to validate somehow. This task is also logically bound to Date class we‘ve used so far, but still doesn‘t require instantiation of it.

Here is where staticmethod can be useful. Let‘s look at the next piece of code:

@staticmethoddef is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split(‘-‘))try:assert0<= day <=31assert0<= month <=12assert0<= year <=3999exceptAssertionError:returnFalsereturnTrue

So, as we can see from usage of staticmethod, we don‘t have any access to what the class is- it‘s basically just a function, called syntactically like a method, but without access to the object and it‘s internals (fields and another methods), while classmethod does.

Ref

http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for

http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python

http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner

http://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods

时间: 2024-08-05 11:16:41

Python:staticmethod vs classmethod的相关文章

Python中@staticmethod和@classmethod的作用和区别

相同之处:@staticmethod 和@classmethod 都可以直接类名.方法名()来调用,不用在示例化一个类. @classmethod 我们要写一个只在类中运行而不在实例中运行的方法.如果我们想让方法不在实例中运行,可以这么做: def iget_no_of_instance(ins_obj): return ins_obj.__class__.no_inst class Kls(object): no_inst = 0 def __init__(self): Kls.no_inst

Python - 静态函数(staticmethod), 类函数(classmethod), 成员函数 区别(完全解析)

原文地址:http://blog.csdn.net/caroline_wendy/article/details/23383995 静态函数(staticmethod), 类函数(classmethod), 成员函数的区别(完全解析) 定义: 静态函数(@staticmethod): 即静态方法,主要处理与这个类的逻辑关联, 如验证数据; 类函数(@classmethod):即类方法, 更关注于从类中调用方法, 而不是在实例中调用方法, 如构造重载; 成员函数: 实例的方法, 只能通过实例进行调

python中 staticmethod与classmethod

原文地址https://blog.csdn.net/youngbit007/article/details/68957848 原文地址https://blog.csdn.net/weixin_35653315/article/details/78165645 原文地址https://www.cnblogs.com/1204guo/p/7832167.html 在Python里, 在class里定义的方法可以大致分为三类: 实例方法, 类方法与静态方法. 用一个表格总结如下: 方法类型 修饰 调用

python中@staticmethod、@classmethod和实例方法

1.形式上的异同点: 在形式上,Python中:实例方法必须有self,类方法用@classmethod装饰必须有cls,静态方法用@staticmethod装饰不必加cls或self,如下代码所示: 1 class A(object): 2 def __init__(self, name): 3 self.name = name 4 5 def get_a_object(self): 6 return "get object method:{}".format(self.name)

Python的3个方法:静态方法(staticmethod),类方法(classmethod)和实例方法

Python的方法主要有3个,即静态方法(staticmethod),类方法(classmethod)和实例方法,如下: def foo(x): print "executing foo(%s)"%(x) class A(object): def foo(self,x): print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(cls,x): print "executing cla

Python中的staticmethod和classmethod

在python中,静态方法和类方法都是可以通过类对象和类对象实例访问.但是区别是: @classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法. 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例. 普通对象方法至少需要一个self参数,代表类对象实例 类方法有类变量cls传入,从而可以用cls做一些相关的处理.并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类. 对于类方法,可以通过类来调用,就像C.

Python中@property和@classmethod和@staticmethod

前戏 首先,先要弄清楚一个类里面的,各个组成部分都应该怎么称呼. - 注:可能叫法会不太一样. 关于@property 顾名思义:它的意思为'属性'. 作用: 1:使用它你将会把类方法,变为类属性.并且是只读属性. 2:它会重新实现getter和setter方法. 看代码: class Person: def __init__(self,first_name,last_name): self.first_name = first_name self.last_name = last_name @

知识点 - python 装饰器@staticmethod和@classmethod区别和使用

1.通常来说,我们使用一个类的方法时,首先要实例化这个类,再用实例化的类来调用其方法 class Test(object): """docstring for Test""" def __init__(self, arg=None): super(Test, self).__init__() self.arg = arg def say_hi(self): print('hello wrold') def main(): test = Test(

python @staticmethod和@classmethod的作用与区别

class test: class_name = "test" def __init__(self, name): self.class_name = name def my_print(self, value): print(value + " " +self.class_name) @staticmethod def my_static_print(val): print(val) @classmethod def my_class_print(cls, val