对比python中的staticmethod与classmethod

936 阅读1分钟

转载参考自Geeksforgeeks - class-method-vs-static-method-python

Class Method

A class method receives the class as implicit first argument, just like an instance method receives the instance.

Syntax:

class C(object):
    @classmethod
    def fun(cls, arg1, arg2, ...):
       ....
fun: function that needs to be converted into a class method
returns: a class method for function.

Static Method

A static method does NOT receive an implicit first argument.

Syntax:

class C(object):
    @staticmethod
    def fun(arg1, arg2, ...):
        ...
returns: a static method for function fun.

Class method vs Static Method

  • parameter:
    • A class method takes cls as first parameter
    • A static method needs no specific parameters.
  • class state:
    • A class method can access or modify class state
    • A static method can’t access or modify it.
    • In general, static methods know nothing about class state. They are utility type methods that take some parameters and work upon those parameters. On the other hand, class methods must have class as parameter.
  • decorator
    • use@classmethod decorator to create a class method
    • use@staticmethod decorator to create a static method.

When to use what?

  • class methods: We generally use class method to create factory methods. Factory methods return class object ( similar to a constructor ) for different use cases.
  • We generally use static methods to create utility functions.

Implementation

# Python program to demonstrate 
# use of class method and static method. 
from datetime import date 

class Person: 
	def __init__(self, name, age): 
		self.name = name 
		self.age = age 
	
	# a class method to create a Person object by birth year. 
	@classmethod
	def fromBirthYear(cls, name, year): 
		return cls(name, date.today().year - year) 
	
	# a static method to check if a Person is adult or not. 
	@staticmethod
	def isAdult(age): 
		return age > 18

person1 = Person('mayank', 21) 
person2 = Person.fromBirthYear('mayank', 1996) 

print person1.age 
print person2.age 

# print the result 
print Person.isAdult(22) 

Reference