https://www.runoob.com/python/python-func-classmethod.html https://blog.csdn.net/polyhedronx/article/details/81911548
@staticmethod
和@classmethod
和@abstractmethod
实例化方法需要实例化对象,再调用方法
静态方法和类方法也可使用
@abstractmethod — 抽象方法
含abstractmethod的方法不能实例化,继承了含abstractmethod方法的子类必须复写所有的abstractmethod装饰的方法
@abstractmethod
def set_input(self, input):
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
Parameters:
input (dict): includes the data itself and its metadata information.
"""
pass
@abstractmethod
def forward(self):
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
pass
@abstractmethod
def optimize_parameters(self):
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
pass
类方法是将类本身作为操作对象,而静态方法是独立于类的一个单独函数,只是寄存在一个类名下
@staticmethod — 静态方法
class C(object):
@staticmethod
def f():
print('runoob');
C.f(); # 静态方法无需实例化
cobj = C()
cobj.f() # 也可以实例化后调用
## output:
>>> runoob
>>> runoob
@classmethod — 类方法
也不需要self参数,但第一个参数需要是表示自身类的cls参数
class A(object):
bar = 1
def func1(self):
print ('foo')
@classmethod
def func2(cls):
print ('func2')
print (cls.bar)
cls().func1() # 调用 foo 方法
A.func2() # 不需要实例化
## output:
>>> func2
>>> 1
>>> foo
例子
class A(object):
# 属性默认为类属性(可以给直接被类本身调用)
num = "类属性"
# 实例化方法(必须实例化类之后才能被调用)
def func1(self): # self : 表示实例化类后的地址id
print("func1")
print(self)
# 类方法(不需要实例化类就可以被类本身调用)
@classmethod
def func2(cls): # cls : 表示没用被实例化的类本身
print("func2")
print(cls)
print(cls.num)
cls().func1()
# 不传递传递默认self参数的方法(该方法也是可以直接被类调用的,但是这样做不标准)
def func3():
print("func3")
print(A.num) # 属性是可以直接用类本身调用的
# A.func1() 这样调用是会报错:因为func1()调用时需要默认传递实例化类后的地址id参数,如果不实例化类是无法调用的
A.func2()
A.func3()
func2
<class '__main__.A'>
类属性
func1
<__main__.A object at 0x0000023701BB16A0>
--------------------------------------------------------------------------
func3
类属性