python 中@staticmethod and @classmethod
-
对于类中的三种method的区别
a) 类中的正常方法,其中参数包含显示的self 参数–这个函数可以调用使用类的各个属性
b) 通过@staticmethod声明的,属于类的静态方法–调用方法:instance.static_func()/CLASS.static_func()
@staticmethod
static_func(*arg)
c)通过@classmethod声明的,属于类的类方法,
@classmethod
class_func(cls,*arg)–cls是类,调用:instance.class_func(*arg)/CLASS.class_func(*arg) -
对于类中的普通函数,当需要调用的时候必须实例化,对于声明为staticmethod/classmethod ,不需要实例化,直接使用类名调用。
class Method:
def __init__(self,name,age):
self.name=name
self.age=age
def get_name(self):
return (self.name)
@staticmethod
def static_func(lastname):
print('called static func--{}'.format(lastname))
@classmethod
def class_func(cls,num=0):
print('called class func--{}-->{}'.format(cls,num))
class Method_i(Method):
pass
m = Method('bob',20)
n = Method_i('Su',30)
print(m.__dict__)
print(n.__dict__)
m.get_name()
m.static_func('Smith')
Method.static_func('Smith')
m.class_func(80)
Method.class_func(90)
print("*"*10)
n.get_name()
n.static_func('Sue')
Method_i.static_func('Sue')
n.class_func(100)
output:
{‘name’: ‘bob’, ‘age’: 20}
{‘name’: ‘Su’, ‘age’: 30}
called static func–Smith
called static func–Smith
called class func–<class ‘main.Method’>–>80
called class func–<class ‘main.Method’>–>90
called static func–Sue
called static func–Sue
called class func–<class ‘main.Method_i’>–>100