[Python] 类函数 & 静态函数

成员函数

  • 参数self代表当前对象的引用
  • 实现查询/修改类的属性等功能

类函数

  • 参数cls表示必须传一个类进来
  • 用于实现不同的init构造函数
  • 需要装饰器@classmethod声明

静态函数

  • 不访问修改类的属性,又不想放到类的外面
  • 用于做一些简单独立的任务,方便测试
  • 需要装饰器@staticmethod声明
 1 class Document():
 2     WELCOME_STR = 'Welcome! The context for this book is{}.'
 3     
 4     def __init__(self, title, author, context):
 5         print('init function called')
 6         self.title = title
 7         self.author = author
 8         self.__context = context
 9         
10     # 类函数
11     @classmethod
12     def create_empty_book(cls, title, author):
13         return cls(title=title, author=author, context='nothing')
14         
15     # 成员函数
16     def get_context_length(self):
17         return len(self.__context)
18         
19     # 静态函数
20     @staticmethod
21     def get_welcome(context):
22         return Document.WELCOME_STR.format(context)
23         
24 empty_book = Document.create_empty_book('What Every Man Thinks About Apart from Sex', 'Professor Sheridan Simove')
25 
26 print(empty_book.get_context_length())
27 print(empty_book.get_welcome('indeed nothing'))        
View Code

 

posted @ 2021-07-29 15:33  cxc1357  阅读(133)  评论(0)    收藏  举报