Python基础——@staticmethod与@classmethod
来源:互联网 发布:丹朱围棋软件 编辑:程序博客网 时间:2024/06/06 02:17
@staticmethod与隐式的静态成员方法的区别在于是否允许实例对象调用该静态方法(后者是不允许的)
@staticmethod与@classmethod的区别在于后者无论是被实例调用还是被类对象调用传递进来的第一个参数永远是类对象(class object)
@staticmethod的用法
使用@staticmethod
声明的成员函数具有C++类的静态成员函数的相同的用法,既可以被对象调用,更可以被类本身调用,因为静态成员函数属于类本身。
在python类的定义中,在成员函数的参数列表中如果不指定第一个参数为self
(也即c++中的this
指针),标识着该方法属于类的方法,但与@staticmethod
的不同之处在于,不可被对象调用。
class Dog(object): count = 0 dogs = [] def __init__(self, name): self.name = name Dog.count += 1 Dog.dogs.append(name) def bar(self, n): print('{} says {}'.format(self.name, 'bar'*n)) def rollCall(n): # this is a implicitly a class method print('There are {} dog.'.format(Dog.count)) if n >= Dog.count or n < 0: print('They are :') for dog in Dog.dogs: print(' {}'.format(dog)) else: print('The dog indexed {} is {}'.format(n, Dog.dogs[n]))if __name__ == '__main__': fido = Dog('Fido') Dog.rollCall(0) # 正确 fido.rollCall(0) # 抛异常
如果将rollCall()
声明为@staticmethod
,使用实例对象也可调用该方法。
@staticmethod与@classmethod的差异
注意区别类对象(class object)与实例对象(instance object)
class Kls(object): no_inst = 0 def __init__(self): Kls.no_inst += 1 @classmethod def get_no_of_instance(cls_obj): return cls_obj.no_instik1 = Kls()ik2 = Kls()print(ik1.get_no_of_instance()) # 2print(Kls.get_no_of_instance()) # 2
使用@classmethod
成员函数的一大优势在于,无论是通过实例对象(instance object,如ik1)还是通过类对象(class object,如Kls)调用该类型方法时,传递进来的第一个参数总是该类对象(也就是将Kls传递给cls_obj)。
0 0
- Python基础——@staticmethod与@classmethod
- Python 基础 —— @classmethod 与 @staticmethod 的意义及用途
- Python中的staticmethod与classmethod
- [基础] - Python中 @staticmethod 和 @classmethod
- 理解python的staticmethod与classmethod实现
- Python中classmethod与staticmethod区别
- Python中classmethod与staticmethod区别
- 理解python的staticmethod与classmethod实现
- Python: classmethod & staticmethod 区别
- Python: classmethod & staticmethod 区别
- 】Python @classmethod @staticmethod
- python staticmethod和classmethod
- python classmethod staticmethod
- Python @staticmethod和@classmethod
- Python @classmethod @staticmethod
- python的staticmethod、classmethod
- Python staticmethod and classmethod
- 【转】Python @classmethod @staticmethod
- lightoj 1080 Binary Simulation (线段树区间更新)
- 解密Apache HAWQ ——功能强大的SQL-on-Hadoop引擎 [作者:常雷]
- 读书笔记--IPC机制(一)
- Android——自定义通知栏使用
- 使用Enterprise Architect 设计数据库
- Python基础——@staticmethod与@classmethod
- JS判断是否是微信页面,判断手机操作系统(ios或android)并跳转到不同下载页面
- 【蓝桥杯】【组素数】
- CSS代码重置浏览器默认样式
- 【鸟哥读书笔记】Linux 文件权限及相关操作
- 亲身实践解决 : insmod hello.ko -1 Invalid module format 的问题
- hdu 1874 畅通工程续(dijkstr朴素)
- 溢出 隐式转换 负数存储
- 快速排序的基本思想及其java的实现