装潢器@staticmethod和@classmethod有什么区别【Python教程】,python
作者:搜教程发布时间:2019-11-27分类:Python教程浏览:33评论:0
导读:一般来讲,我们运用一个类的要领时,起首要实例化这个类,再用实例化的类来挪用其要领classTest(object):"""docstringforTest"...
一般来讲,我们运用一个类的要领时,起首要实例化这个类,再用实例化的类来挪用其要领
class Test(object): """docstring for Test""" def __init__(self, arg=None): super(Test, self).__init__() self.arg = arg def say_hi(self): print 'hello wrold' def main(): test = Test() //1. 起首实例化test类 test.say_hi() //2. 再挪用类的要领 if __name__ == '__main__': main()
而运用@staticmethod或@classmethod,就能够不须要实例化,直接类名.要领名()来挪用。
这有利于构造代码,把某些应当属于某个类的函数给放到谁人类里去,同时有利于定名空间的整齐。
class Test(object): """docstring for Test""" def __init__(self, arg=None): super(Test, self).__init__() self.arg = arg def say_hi(self): print 'hello wrold' @staticmethod def say_bad(): print 'say bad' @classmethod def say_good(cls): print 'say good' def main(): test = Test() test.say_hi() Test.say_bad() //直接类名.要领名()来挪用 Test.say_good() //直接类名.要领名()来挪用 if __name__ == '__main__': main()
@staticmethod或@classmethod的区分
类的一般要领,地一个参数须要self参数示意本身。
@staticmethod不须要示意本身对象的self和本身类的cls参数,就跟运用函数一样。
@classmethod也不须要self参数,但第一个参数须如果示意本身类的cls参数。
以上就是装潢器@staticmethod和@classmethod有什么区分的细致内容,更多请关注ki4网别的相干文章!
标签:python
相关推荐
- python数据类型有哪几种?_Python教程,python
- python针对Excel表格的操作_Python教程,python,excel
- 实例解析Python单元测试及unittest框架用法_Python教程,python,单元测试,unittest框架
- Python如何使用xlrd实现读取合并单元格_Python教程,python,xlrd
- 手把手教你在python中如何使用while True语句_Python教程,python,while true
- 给大家分享一下日常学习python的心得(详解)_Python教程,python
- python如何另起一行?_Python教程,python
- python是一种跨平台、开源、免费的高级动态编程语言,对么_Python教程,python,跨平台,开源,免费,编程语言
- 关于python装饰器的详细介绍_Python教程,python,装饰器
- 推荐几个适合小白学习Python的免费网站_Python教程,python,网站
你 发表评论:
欢迎- Python教程排行
-
- 1python数据类型有哪几种?_Python教程,python
- 2python如何批量处理excel数据?_Python教程,python,excel数据
- 3python针对Excel表格的操作_Python教程,python,excel
- 4在python中导入其它函数库的关键字是什么_Python教程,python,函数库,关键字
- 5手把手教你在python中如何使用while True语句_Python教程,python,while true
- 6给大家分享一下日常学习python的心得(详解)_Python教程,python
- 7python中if语句用法_Python教程,python,if语句
- 8实例解析Python单元测试及unittest框架用法_Python教程,python,单元测试,unittest框架
- 9详细分析之Python可变对象和不可变对象_Python教程,Python,可变对象,不可变对象
- 最新文章
- 广而告之