Python 静态方法和类方法的区别

python staticmethod and classmethod

Though classmethod and staticmethod are quite similar, there’s a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.

Let’s look at all that was said in real examples.

尽管 classmethod 和 staticmethod 非常相似,但在用法上依然有一些明显的区别。classmethod 必须有一个指向 类对象 的引用作为第一个参数,而 staticmethod 可以没有任何参数。

让我们看几个例子。

例子 – Boilerplate

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

Python

1

2

3

4

5

6

class Date(object):

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).

很明显,这个类的对象可以存储日期信息(不包括时区,假设他们都存储在 UTC)。

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

这里的 init 方法用于初始化对象的属性,它的第一个参数一定是 self,用于指向已经创建好的对象。

Class Method

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.

利用 classmethod 可以做一些很棒的东西。

比如我们可以支持从特定格式的日期字符串来创建对象,它的格式是 (‘dd-mm-yyyy’)。很明显,我们只能在其他地方而不是 init 方法里实现这个功能。

So what we must do here is:
Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
Instantiate Date by passing those values to initialization call.
This will look like:

大概步骤:

  • 解析字符串,得到整数 day, month, year。
  • 使用得到的信息初始化对象

代码如下

Python

1

2

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

date1 = Date(day, month, year)

理想的情况是 Date 类本身可以具备处理字符串时间的能力,解决了重用性问题,比如添加一个额外的方法。

For this purpose, C++ has such feature as overloading, but Python lacks that feature- so here’s when classmethod applies. Lets create another “constructor”.

C++ 可以方便的使用重载来解决这个问题,但是 python 不具备类似的特性。 所以接下来我们要使用 classmethod 来帮我们实现。

Python

1

2

3

4

5

6

7

8

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

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

We’ve implemented date string parsing in one place and it’s reusable now.
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).
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.

让我们在仔细的分析下上面的实现,看看它的好处。

我们在一个方法中实现了功能,因此它是可重用的。 这里的封装处理的不错(如果你发现还可以在代码的任意地方添加一个不属于 Date 的函数来实现类似的功能,那很显然上面的办法更符合 OOP 规范)。 cls 是一个保存了 class 的对象(所有的一切都是对象)。 更妙的是, Date 类的衍生类都会具有 from_string 这个有用的方法。

Static method

What about staticmethod? It’s pretty similar to classmethod but doesn’t take any obligatory parameters (like a class method or instance method 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:

staticmethod 没有任何必选参数,而 classmethod 第一个参数永远是 cls, instancemethod 第一个参数永远是 self。

Python

1

2

3

4

5

6

7

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

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.

所以,从静态方法的使用中可以看出,我们不会访问到 class 本身 – 它基本上只是一个函数,在语法上就像一个方法一样,但是没有访问对象和它的内部(字段和其他方法),相反 classmethod 会访问 cls, instancemethod 会访问 self。

参考

时间: 2024-08-29 06:27:09

Python 静态方法和类方法的区别的相关文章

python 静态方法、类方法(二)

<Python静态方法.类方法>一文中曾用在类之外生成函数的方式,来计算类的实例的个数.本文将探讨用静态方法和类方法来实现此功能. 一使用静态方法统计实例 例1.static.py # -*- coding:utf-8 -*- class Spam: numInstance = 0 def __init__(self): Spam.numInstance += 1 def printNumInstance(): print 'Number of instance:', Spam.numInst

Python 静态方法、类方法

今天我们来讨论一下Python类中所存在的特殊方法--静态方法.类方法. 一.定义 静态方法: 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静态方法都不会接受自动的self参数. 2.会记录所有实例的信息,而不是为实例提供行为. 类方法: 一种函数,符合以下特征 1.类调用.或实例调用,传递的参数是一个类对象. 二.需要特殊方法的情况(用途) 程序需要处理与类而不是与实例相关的数据.也就是说这种数据信息通常存储在类自身上,不需要任何实例也

python静态方法和类方法

静态方法是类和类的独立实例.它是在类范围中定义的方法. 它可以直接由类和实例被称为. 类方法和静态方法都要使用装饰器来定义,定义的基本格式是: @staticmethod def <function name>(): #do something 类方法定义的基本格式是: @ classmethod def <function name>(cls): #do something 类方法与成员方法不同的是,它须要传入參数cls,cls代表类. class Myclass(): x='c

python中的静态方法和类方法的区别【转】

class TestClassMethod(object): METHOD = 'method hoho' def __init__(self): self.name = 'leon' def test1(self): print 'test1' print self @classmethod def test2(cls): print cls print 'test2' print TestClassMethod.METHOD print '----------------' @staticm

python 静态方法与类方法

#!/usr/bin/python #-*- coding: utf-8 -*- class Pizza(object):     a="AA"     def __init__(self):         self.name = 'leon'     def cook(self):         return self.mix_ingredients(self.cheese, self.vegetables)     @staticmethod     def mix_ingre

Python静态方法、类方法、属性方法

静态方法 使用静态方法以后,相当于把下面的函数和类的关系截断了,它的作用相当于是类下面的一个独立函数,不会自动传入参数self. class people:..... @staticmethod def xxx(): pass 类方法 只能访问类变量,不能访问实例变量. @classmethod class dog: name = "小黑" def __init__(self,name): self.name = name @classmethod def hit(cls): prin

python类的静态方法和类方法区别

# python类的静态方法和类方法区别 ## 先看语法,python 类语法中有三种方法,实例方法,静态方法,类方法. 本文由黄哥python培训黄哥所写. # coding:utf-8 class Foo(object): """类三种方法语法形式""" def instance_method(self): print("是类{}的实例方法,只能被实例对象调用".format(Foo)) @staticmethod def

Python的类方法,静态方法,实例方法的区别

Python的方法并不想C#,Java这些编译性语言那样严格的区分静态方法和实例方法.也就是说Python的静态方法,类方法和实例方法只是在调用上有区别,类型和实例都可以调用.一般规则如下:A:实例方法:没有@classmethod和@staticmethod标记的方法是实例方法.假设这个有n个比传参数,类型调用的时候需要给n个参数传参.而实例调用时则只能传n-1个参数,因为第一个参数被系统默认传递了实例本身:因为有这个规定,所以实例方法如果没有参数,则实例是无法调用的,但类型可以调用.B:类方

python中静态方法、类方法、属性方法区别

在python中,静态方法.类方法.属性方法,刚接触对于它们之间的区别确实让人疑惑. 类方法(@classmethod) 是一个函数修饰符,表是该函数是一个类方法 类方法第一个参数是cls,而实例方法第一个参数是self(表示该类的一个实例) 类中普通函数至少要一个self参数,代表类对象实例 类方法至少需要一个cls参数,通过cls可以获取到类本身的属性方法等元信息.当有个子类继承时,传入的是子类对象. 对于类方法两种调用方式,类.func(),类实例.func() 静态方法(@staticm