The official explanation
- @classmethod
A class class method to itself as the first argument, as an example of a method to Example themselves as the first argument.
语法格式:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
- @staticmethod
Static method does not receive an implicit first parameter.
语法格式:
class C:
@staticmethod
def f(arg1, arg2, ...): ...
characteristic
Same point
- Not instantiate the class directly call
import time
class School(object):
school_name = "A_Tester_School"
address = "China_Sichuan"
def __init__(self, student_name):
self.student_name = "a student of A_Tester_School, name is: {} ".format(student_name)
def age(self, birthday):
return time.localtime().tm_year - birthday
@classmethod
def get_school(cls):
return cls.school_name, cls.address
@staticmethod
def get_address():
return "hello world."
# 实例调用
my_school = School("Hoo")
print(my_school.age(1991))
print(my_school.get_school())
print(my_school.get_address())
print("-"*50)
# 不实例化调用
print(School.get_school())
print(School.get_address())
# 28
# ('A_Tester_School', 'China_Sichuan')
# hello world.
# --------------------------------------------------
# ('A_Tester_School', 'China_Sichuan')
# hello world.
difference
category | @classmethod | @staticmethod |
---|---|---|
Syntax | The at least one parameter, the first parameter is the class itself | Can be no argument |
Personal understanding
- Difference between the two
- staticmethod decorative function is a normal function, the class is not half dime nature can not be used so that a local variable class. (eg: School class school_name), etc. can not be operated.
- classmethod decorative function into a first parameter of the class itself, and therefore operable type, including a decorative function staticmethod reference to the class.
class ChildSchool(School):
@classmethod
def get_student_info(cls, student_name, birthday):
my_school = cls(student_name) # 实例化类
age1 = my_school.age(birthday) # 调用实例方法
print("school_name: {}".format(cls.school_name)) # 不实例类, 调用类局部变量
print("address: {}".format(my_school.address)) # 实例类, 调用类局部变量. 此处my_school可换成cls
print("age: {}".format(age1))
print("introduction: {}".format(my_school.student_introduction)) # 调用实例属性
print("this a error address: {}".format(cls.get_address())) # 调用类静态方法
ChildSchool.get_student_info("Hoo", 1991)
# school_name: A_Tester_School
# address: China_Sichuan
# age: 28
# introduction: a student of A_Tester_School, name is: Hoo
# this a error address: hello world.