zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    网页CSS2
    C#(1)—类型、常量及变量
    进制转化
    12月26日提纲
    12月24日笔记
    12月23日笔记
    12月22日笔记
    12月21日笔记
    12月20日笔记
    break、continue与数组
  • 原文地址:https://www.cnblogs.com/cxc1357/p/12708320.html
Copyright © 2011-2022 走看看