https://www.runoob.com/python/python-func-classmethod.html https://blog.csdn.net/polyhedronx/article/details/81911548

@staticmethod@classmethod@abstractmethod

实例化方法需要实例化对象,再调用方法
静态方法和类方法也可使用

@abstractmethod — 抽象方法

含abstractmethod的方法不能实例化,继承了含abstractmethod方法的子类必须复写所有的abstractmethod装饰的方法

  1. @abstractmethod
  2. def set_input(self, input):
  3. """Unpack input data from the dataloader and perform necessary pre-processing steps.
  4. Parameters:
  5. input (dict): includes the data itself and its metadata information.
  6. """
  7. pass
  8. @abstractmethod
  9. def forward(self):
  10. """Run forward pass; called by both functions <optimize_parameters> and <test>."""
  11. pass
  12. @abstractmethod
  13. def optimize_parameters(self):
  14. """Calculate losses, gradients, and update network weights; called in every training iteration"""
  15. pass

类方法是将类本身作为操作对象,而静态方法是独立于类的一个单独函数,只是寄存在一个类名下

@staticmethod — 静态方法

  1. class C(object):
  2. @staticmethod
  3. def f():
  4. print('runoob');
  5. C.f(); # 静态方法无需实例化
  6. cobj = C()
  7. cobj.f() # 也可以实例化后调用
  8. ## output:
  9. >>> runoob
  10. >>> runoob

@classmethod — 类方法

也不需要self参数,但第一个参数需要是表示自身类的cls参数

  1. class A(object):
  2. bar = 1
  3. def func1(self):
  4. print ('foo')
  5. @classmethod
  6. def func2(cls):
  7. print ('func2')
  8. print (cls.bar)
  9. cls().func1() # 调用 foo 方法
  10. A.func2() # 不需要实例化
  11. ## output:
  12. >>> func2
  13. >>> 1
  14. >>> foo

例子

  1. class A(object):
  2. # 属性默认为类属性(可以给直接被类本身调用)
  3. num = "类属性"
  4. # 实例化方法(必须实例化类之后才能被调用)
  5. def func1(self): # self : 表示实例化类后的地址id
  6. print("func1")
  7. print(self)
  8. # 类方法(不需要实例化类就可以被类本身调用)
  9. @classmethod
  10. def func2(cls): # cls : 表示没用被实例化的类本身
  11. print("func2")
  12. print(cls)
  13. print(cls.num)
  14. cls().func1()
  15. # 不传递传递默认self参数的方法(该方法也是可以直接被类调用的,但是这样做不标准)
  16. def func3():
  17. print("func3")
  18. print(A.num) # 属性是可以直接用类本身调用的
  19. # A.func1() 这样调用是会报错:因为func1()调用时需要默认传递实例化类后的地址id参数,如果不实例化类是无法调用的
  20. A.func2()
  21. A.func3()
  1. func2
  2. <class '__main__.A'>
  3. 类属性
  4. func1
  5. <__main__.A object at 0x0000023701BB16A0>
  6. --------------------------------------------------------------------------
  7. func3
  8. 类属性